<?php
namespace EasyChat\Library\Email;

use EasyChat\Library\RequestContext;

 
final class EmailSenderAddressAdvisor {
    public function advise(array $config,array $outbound): array {
        if(empty($outbound['success']))return array();
        $current=$this->email((string)($config['sender_email']??''));
        $mailbox=$this->email((string)($config['email_address']??''));
        $transport=(string)($outbound['transport']??$config['outbound_transport']??'');
        $candidate='';$reason='';$source='';$verified=false;

        if($transport==='direct_smtp'){
            $candidate=$mailbox;$reason='Совпадает с проверенным SMTP-ящиком.';$source='mailbox';$verified=true;
        }elseif($transport==='cms_mail'){
            $candidate=$this->email((string)($outbound['sender_email']??''));
            if($candidate!==''){$reason='Настроен в почте сайта.';$source='cms';$verified=true;}
            else{$candidate=$this->domainCandidate();$reason='Соответствует домену магазина.';$source='site_domain';}
        }elseif($transport==='local_relay'){
            $candidate=$this->domainCandidate();$reason='Лучше подходит для почты хостинга.';$source='site_domain';
        }elseif($transport==='smtp_bz_api'){
            $candidate=$current;$reason='Домен подтверждён выбранным сервисом.';$source='selected_transport';$verified=true;
        }

        if($candidate===''||$candidate===$current)return array();
        return array('email'=>$candidate,'reason'=>$reason,'source'=>$source,'verified'=>$verified,'transport'=>$transport,'action'=>'apply_sender_email');
    }

    private function domainCandidate(): string {
        $url=defined('HTTP_SERVER')?(string)HTTP_SERVER:'';
        $host=strtolower((string)(parse_url($url,PHP_URL_HOST)?:''));
        $server=RequestContext::server();
        if($host==='')$host=strtolower(preg_replace('/:\d+$/','',(string)($server['HTTP_HOST']??'')));
        $host=preg_replace('/^www\./','',$host);
        if($host===''||$host==='localhost'||filter_var($host,FILTER_VALIDATE_IP)||!preg_match('/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i',$host))return '';
        return 'support@'.$host;
    }

    private function email(string $value): string {
        $value=strtolower(trim($value));
        return filter_var($value,FILTER_VALIDATE_EMAIL)&&strlen($value)<=254?$value:'';
    }
}
