<?php
declare(strict_types=1);
namespace App\Mailer;

use App\Settings\SettingsRepository;

final class SmtpDiagnosticService
{
    public function __construct(private readonly SettingsRepository $settings) {}
    /** @return array<string,array{status:string,detail:string}> */
    public function inspect(bool $network = false): array
    {
        $enabled=(bool)$this->settings->get('mail.enabled',false);$transport=strtolower((string)$this->settings->get('mail.transport','mail'));
        $host=trim((string)$this->settings->get('mail.smtp.host',''));$port=max(1,(int)$this->settings->get('mail.smtp.port',587));
        $user=trim((string)$this->settings->get('mail.smtp.username',''));$from=trim((string)$this->settings->get('mail.from_email',''));
        $rows=['configuration'=>['status'=>($enabled?'pass':'warn'),'detail'=>$enabled?'Mail delivery enabled.':'Mail delivery is disabled.']];
        if(!$enabled||$transport!=='smtp'){ $rows['transport']=['status'=>'info','detail'=>$transport==='smtp'?'SMTP selected.':'PHP mail transport selected.']; return $rows; }
        $rows['smtp_fields']=['status'=>($host!==''&&$user!==''&&filter_var($from,FILTER_VALIDATE_EMAIL)?'pass':'fail'),'detail'=>'SMTP host, username and sender address validation.'];
        $rows['openssl']=['status'=>extension_loaded('openssl')?'pass':'fail','detail'=>extension_loaded('openssl')?'OpenSSL available.':'OpenSSL extension unavailable.'];
        if(!$network){$rows['network']=['status'=>'info','detail'=>'Live SMTP connection test not requested.'];return $rows;}
        if($host===''){ $rows['tcp']=['status'=>'fail','detail'=>'SMTP host is empty.']; return $rows; }
        $start=microtime(true);$socket=@stream_socket_client('tcp://'.$host.':'.$port,$errno,$errstr,5,STREAM_CLIENT_CONNECT);
        if(!is_resource($socket)){$rows['tcp']=['status'=>'fail','detail'=>'TCP connection failed (code '.(int)$errno.').'];return $rows;}
        fclose($socket);$rows['tcp']=['status'=>'pass','detail'=>'TCP connection succeeded in '.(int)round((microtime(true)-$start)*1000).' ms.'];return $rows;
    }
}
