<?php

namespace App\Base\Config\Auth;

use App\Base\Config\ConfigInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

class OidcConfig implements ConfigInterface
{
    private array $messages = [];

    public function __construct(
        #[Autowire(param: 'auth.method')]
        private readonly ?string $authMethod = null,

        #[Autowire(param: 'auth.oidc.well_known_url')]
        private readonly ?string $wellKnownUrl = null,

        #[Autowire(param: 'auth.oidc.client_id')]
        private readonly ?string $clientId = null,

        #[Autowire(param: 'auth.oidc.client_secret')]
        private readonly ?string $clientSecret = null,

        #[Autowire(param: 'auth.oidc.bypass_form_login')]
        private readonly ?bool $bypassFormLogin = null,
    ) {}

    public function isEnabled(): bool
    {
        return "oidc" === strtolower($this->authMethod);
    }

    public function isValid(): bool
    {
        $valid = true;

        if (true === $this->isEnabled()) {
            if (false === $this->isVariableValid("OIDC_CLIENT_ID", $this->clientId)) {
                $valid = false;
            }

            if (false === $this->isVariableValid("OIDC_CLIENT_SECRET", $this->clientSecret)) {
                $valid = false;
            }

            if (false === $this->isVariableValid("OIDC_WELL_KNOWN_URL", $this->wellKnownUrl)) {
                $valid = false;
            }
        }

        return $valid;
    }

    public function getWellKnownUrl(): ?string
    {
        return $this->wellKnownUrl;
    }

    public function getClientId(): ?string
    {
        return $this->clientId;
    }

    public function getClientSecret(): ?string
    {
        return $this->clientSecret;
    }

    public function getBypassFormLogin(): ?bool
    {
        return $this->bypassFormLogin;
    }

    public function getMessages(): array
    {
        return $this->messages;
    }

    private function isVariableValid(string $key, mixed $value): bool
    {
        if ("" === $value || null === $value) {
            $this->messages[] = "Your OIDC is misconfigured. Please set the $key environment variable to the required value.";
            return true;
        }
        return false;
    }
}
