<?php

namespace App\Support;

class SmtpConfig
{
    /**
     * Normalize UI SMTP settings into the mailer config keys that the current
     * Laravel / Symfony mail stack actually reads.
     *
     * @param  array{
     *   host?: string|null,
     *   port?: int|null,
     *   username?: string|null,
     *   password?: string|null,
     *   encryption?: string|null,
     *   timeout?: int|null,
     *   local_domain?: string|null
     * }  $config
     * @return array<string, mixed>
     */
    public static function build(array $config): array
    {
        $port = (int) ($config['port'] ?? 587);
        $encryption = strtolower(trim((string) ($config['encryption'] ?? 'tls')));

        $mailer = [
            'transport' => 'smtp',
            'host' => (string) ($config['host'] ?? ''),
            'port' => $port,
            'username' => $config['username'] ?? null,
            'password' => $config['password'] ?? null,
        ];

        if (!empty($config['timeout'])) {
            $mailer['timeout'] = (int) $config['timeout'];
        }

        if (!empty($config['local_domain'])) {
            $mailer['local_domain'] = (string) $config['local_domain'];
        }

        switch ($encryption) {
            case 'ssl':
                $mailer['scheme'] = 'smtps';
                $mailer['auto_tls'] = false;
                $mailer['require_tls'] = false;
                break;

            case 'none':
            case '':
                $mailer['scheme'] = 'smtp';
                $mailer['auto_tls'] = false;
                $mailer['require_tls'] = false;
                break;

            case 'tls':
                $mailer['scheme'] = 'smtp';
                $mailer['auto_tls'] = true;
                $mailer['require_tls'] = true;
                break;

            default:
                $mailer['scheme'] = $port === 465 ? 'smtps' : 'smtp';
                break;
        }

        return $mailer;
    }
}
