<?php

namespace App\Services\Installer;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Mail;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Throwable;

class SmtpConnectionTester
{
    /**
     * @param  array<string, mixed>  $config
     * @return array{success: bool, message: ?string}
     */
    public function test(array $config): array
    {
        try {
            Config::set('mail.default', $config['mailer'] ?? 'smtp');
            Config::set('mail.mailers.smtp', [
                'transport' => 'smtp',
                'host' => $config['host'] ?? '127.0.0.1',
                'port' => $config['port'] ?? 587,
                'encryption' => $config['encryption'] ?? 'tls',
                'username' => $config['username'] ?? null,
                'password' => $config['password'] ?? null,
                'timeout' => null,
            ]);

            $transport = Mail::mailer()->getSymfonyTransport();
            if (method_exists($transport, 'start')) {
                $transport->start();
                if (method_exists($transport, 'stop')) {
                    $transport->stop();
                }
            }

            return ['success' => true, 'message' => null];
        } catch (TransportExceptionInterface $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        } catch (Throwable $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }
}
