<?php

namespace MintyPHP\Module\Helpdesk\Service;

/**
 * Immutable value object holding the fully resolved helpdesk BC connection config.
 *
 * Created by EffectiveHelpdeskSettingsService — consumers read this instead
 * of reaching into global or tenant settings directly.
 */
final class EffectiveHelpdeskSettings
{
    /**
     * @param 'global'|'tenant' $source
     */
    public function __construct(
        public readonly string $source,
        public readonly string $authMode,
        public readonly string $odataBaseUrl,
        public readonly string $companyName,
        public readonly ?string $basicUser,
        public readonly ?string $basicPassword,
        public readonly ?string $oauthTenantId,
        public readonly ?string $oauthClientId,
        public readonly ?string $oauthClientSecret,
        public readonly ?string $oauthTokenEndpoint,
        public readonly ?string $systemRecommendationsConfigRaw,
        public readonly ?string $controllingRiskConfigRaw,
    ) {
    }

    public function buildEntityUrl(string $entitySet): string
    {
        $company = rawurlencode($this->companyName);

        return $this->odataBaseUrl . "/Company('" . $company . "')/" . $entitySet;
    }

    /**
     * @return array<string> List of missing setting descriptions (empty = valid)
     */
    public function validateConfiguration(): array
    {
        $missing = [];

        if ($this->basicUser === null && $this->authMode === HelpdeskSettingsGateway::AUTH_MODE_BASIC) {
            $missing[] = 'BC Basic Auth User';
        }
        if ($this->basicPassword === null && $this->authMode === HelpdeskSettingsGateway::AUTH_MODE_BASIC) {
            $missing[] = 'BC Basic Auth Password';
        }
        if ($this->authMode === HelpdeskSettingsGateway::AUTH_MODE_OAUTH2) {
            if ($this->oauthClientId === null) {
                $missing[] = 'BC OAuth2 Client ID';
            }
            if ($this->oauthClientSecret === null) {
                $missing[] = 'BC OAuth2 Client Secret';
            }
            if ($this->oauthTokenEndpoint === null) {
                $missing[] = 'BC OAuth2 Token Endpoint';
            }
        }

        return $missing;
    }

    public function isConfigured(): bool
    {
        return $this->validateConfiguration() === [];
    }
}
