<?php

declare(strict_types=1);

namespace UFPE\GoogleOIDC;

final class Config
{
    public const OPTION = 'ufpe_google_oidc_settings';
    public const META_SUB = '_ufpe_google_sub';
    public const META_EMAIL = '_ufpe_google_email';
    public const META_HD = '_ufpe_google_hd';
    public const META_PICTURE = '_ufpe_google_picture';
    public const META_LAST_LOGIN = '_ufpe_google_last_login';
    public const META_PROVISIONED = '_ufpe_google_provisioned';
    public const META_BLOCKED = '_ufpe_google_blocked';
    public const META_LOCAL_ADMIN = '_ufpe_google_local_admin_allowed';

    public static function defaults(): array
    {
        return [
            'client_id' => '',
            'client_secret' => '',
            'allowed_domain' => 'ufpe.br',
            'primary_admin_email' => 'daniel.vieira@ufpe.br',
            'administrator_emails' => "daniel.vieira@ufpe.br\nthiago.prazeres@ufpe.br",
            'auto_provision' => '1',
            'default_role' => 'subscriber',
            'link_existing_by_email' => '1',
            'restrict_password_login' => '0',
        ];
    }

    public function all(): array
    {
        $saved = get_option(self::OPTION, []);
        return wp_parse_args(is_array($saved) ? $saved : [], self::defaults());
    }

    public function get(string $key): string
    {
        $settings = $this->all();
        return (string) ($settings[$key] ?? '');
    }

    public function clientId(): string
    {
        return defined('UFPE_GOOGLE_OIDC_CLIENT_ID')
            ? (string) constant('UFPE_GOOGLE_OIDC_CLIENT_ID')
            : $this->get('client_id');
    }

    public function clientSecret(): string
    {
        return defined('UFPE_GOOGLE_OIDC_CLIENT_SECRET')
            ? (string) constant('UFPE_GOOGLE_OIDC_CLIENT_SECRET')
            : $this->get('client_secret');
    }

    public function allowedDomain(): string
    {
        return strtolower($this->get('allowed_domain') ?: 'ufpe.br');
    }

    public function autoProvision(): bool
    {
        return $this->get('auto_provision') === '1';
    }

    public function linkExistingByEmail(): bool
    {
        return $this->get('link_existing_by_email') === '1';
    }

    public function restrictPasswordLogin(): bool
    {
        return $this->get('restrict_password_login') === '1';
    }

    public function defaultRole(): string
    {
        $role = $this->get('default_role') ?: 'subscriber';
        return wp_roles()->is_role($role) ? $role : 'subscriber';
    }

    public function primaryAdminEmail(): string
    {
        return strtolower(sanitize_email($this->get('primary_admin_email')));
    }

    public function administratorEmails(): array
    {
        $raw = preg_split('/[\s,;]+/', strtolower($this->get('administrator_emails')));
        $emails = array_filter(array_map('sanitize_email', is_array($raw) ? $raw : []));

        return array_values(array_unique($emails));
    }

    public function isAdministratorEmail(string $email): bool
    {
        return in_array(strtolower(sanitize_email($email)), $this->administratorEmails(), true);
    }

    public function redirectUri(): string
    {
        return add_query_arg(
            ['action' => AuthController::CALLBACK_ACTION],
            network_site_url('wp-login.php', 'login')
        );
    }

    public function startUri(string $redirectTo = ''): string
    {
        $args = ['action' => AuthController::START_ACTION];

        if ($redirectTo !== '') {
            $args['redirect_to'] = $redirectTo;
        }

        return add_query_arg($args, network_site_url('wp-login.php', 'login'));
    }
}
