<?php

namespace App\Services\Email;

class EmailProfileService
{
    public function resolveProfile(?string $profile): string
    {
        $p = strtolower(trim((string) $profile));
        if ($p === '' || $p === 'auto') {
            $p = strtolower((string) env('MAIL_PROFILE_DEFAULT', 'default')) ?: 'default';
        }

        return match ($p) {
            'comm', 'comms' => 'communication',
            'sys', 'system' => 'default',
            default => $p,
        };
    }

    public function envKeyFromProfile(string $profile): string
    {
        return strtoupper(preg_replace('/[^A-Z0-9]+/i', '_', $profile));
    }

    public function getProfileConfig(string $profile): array
    {
        $key = $this->envKeyFromProfile($profile);

        $envFirst = function (array $keys, $default = null) {
            foreach ($keys as $k) {
                $v = env($k);
                if (is_string($v)) {
                    $v = trim($v);
                }
                if ($v !== null && $v !== '') {
                    return $v;
                }
            }
            return $default;
        };

        $host = $envFirst(["MAIL_{$key}_HOST", 'MAIL_DEFAULT_HOST', 'SMTP_HOST', 'MAIL_HOST'], '');
        $user = $envFirst(["MAIL_{$key}_USER", 'MAIL_DEFAULT_USER', 'SMTP_USER', 'MAIL_USERNAME'], '');
        $pass = $envFirst(["MAIL_{$key}_PASS", 'MAIL_DEFAULT_PASS', 'SMTP_PASS', 'MAIL_PASSWORD'], '');
        $portRaw = $envFirst(["MAIL_{$key}_PORT", 'MAIL_DEFAULT_PORT', 'SMTP_PORT', 'MAIL_PORT'], 587);
        $encRaw = $envFirst(["MAIL_{$key}_ENCRYPTION", 'MAIL_DEFAULT_ENCRYPTION', 'SMTP_ENCRYPTION', 'MAIL_ENCRYPTION'], 'tls');

        $fromEmail = $envFirst(["MAIL_{$key}_FROM_EMAIL", 'MAIL_DEFAULT_FROM_EMAIL', 'MAIL_FROM_ADDRESS'], $user ?: 'no-reply@alrahmaisgl.org');
        $fromName = $envFirst(["MAIL_{$key}_FROM_NAME", 'MAIL_DEFAULT_FROM_NAME', 'MAIL_FROM_NAME'], 'Al Rahma Sunday School');
        $replyTo = $envFirst(["MAIL_{$key}_REPLY_TO", 'MAIL_DEFAULT_REPLY_TO'], '');
        $replyToName = $envFirst(["MAIL_{$key}_REPLY_TO_NAME", 'MAIL_DEFAULT_REPLY_TO_NAME'], '');
        $returnPath = $envFirst(["MAIL_{$key}_RETURN_PATH", 'MAIL_DEFAULT_RETURN_PATH'], '');

        $dkim = [
            'domain' => $envFirst(["MAIL_{$key}_DKIM_DOMAIN", 'MAIL_DEFAULT_DKIM_DOMAIN'], ''),
            'selector' => $envFirst(["MAIL_{$key}_DKIM_SELECTOR", 'MAIL_DEFAULT_DKIM_SELECTOR'], ''),
            'private' => $envFirst(["MAIL_{$key}_DKIM_PRIVATE", 'MAIL_DEFAULT_DKIM_PRIVATE'], ''),
        ];

        $port = (int) $portRaw ?: 587;
        $encryption = strtolower((string) $encRaw);
        $encryption = in_array($encryption, ['tls', 'ssl'], true) ? $encryption : 'tls';

        if ($port === 587 && $encryption === 'ssl') {
            $encryption = 'tls';
        }
        if ($port === 465 && $encryption === 'tls') {
            $encryption = 'ssl';
        }

        return [
            'host' => (string) $host,
            'user' => (string) $user,
            'pass' => (string) $pass,
            'port' => $port,
            'encryption' => $encryption,
            'fromEmail' => (string) $fromEmail,
            'fromName' => (string) $fromName,
            'replyTo' => (string) $replyTo,
            'replyToName' => (string) $this->sanitizeReplyToName($replyToName, (string) $fromName),
            'returnPath' => (string) $returnPath,
            'dkim' => $dkim,
        ];
    }

    public function sanitizeReplyToName(?string $name, string $fallback): string
    {
        $trimmed = trim((string) $name);
        if ($trimmed === '' || preg_match('/^no[- ]?repl(?:y|ay)$/i', $trimmed)) {
            return $fallback;
        }
        return $trimmed;
    }
}
