<?php
namespace EasyChat\Library\Messenger;

use EasyChat\Library\Email\EmailDeliveryEvidenceRepository;
use EasyChat\Library\Email\EmailThreadIndex;
use EasyChat\Library\Email\MailEnvelope;
use EasyChat\Library\Email\OutboundMailTransportResolver;
use EasyChat\Model\EmailAccount;

final class EmailProvider implements MessengerProviderInterface {
    const PROVIDER = 'email';
    private $registry;
    public function __construct($registry = null) { $this->registry=$registry; }
    public function providerCode(): string { return self::PROVIDER; }
    public function getBotInfo(string $token): array { return ['success'=>true,'name'=>'Почта']; }
    public function syncWebhook(array $channel,string $token,string $webhook_url,string $secret): array { return ['success'=>true,'skipped'=>'imap_polling']; }
    public function parseWebhook(array $payload): array { return $payload; }
    public function sendMessage(string $token,string $external_user_id,string $text,array $attachments=[],array $options=[]): array {
        if ($attachments) return ['success'=>false,'error'=>'email_attachments_unsupported'];
        $config=json_decode($token,true);
        if (!is_array($config)||trim($text)==='') return ['success'=>false,'error'=>'email_configuration_invalid'];
        $external_user_id=preg_replace('/#ec:[a-f0-9]{16}$/','',$external_user_id);
        $senderEmail=(string)($config['sender_email']??$config['email_address']??'');
        $messageId='ec.'.bin2hex(random_bytes(16)).'@'.substr(strrchr($senderEmail,'@')?:'@localhost',1);
        $subject=trim((string)($options['subject']??''));$subject=$subject===''?'Ответ EasyChat':(preg_match('/^re\s*:/i',$subject)?$subject:'Re: '.$subject);
        try{$mail=new MailEnvelope(array('to'=>$external_user_id,'from'=>$senderEmail,'from_name'=>(string)($config['display_name']??''),'reply_to'=>(string)$config['email_address'],'subject'=>$subject,'text'=>$text,'message_id'=>$messageId,'in_reply_to'=>(string)($options['in_reply_to']??''),'references'=>(array)($options['references']??array()),'idempotency_key'=>(string)($options['dedupe_key']??'')));}
        catch(\Throwable $e){return array('success'=>false,'error'=>'email_envelope_invalid');}
        $resolver=new OutboundMailTransportResolver($this->registry);
        try{
            if(($config['outbound_transport']??'auto')==='auto'){$probe=$resolver->probe($config);if(empty($probe['success']))return array('success'=>false,'error'=>(string)($probe['code']??'email_outbound_unavailable'),'retryable'=>false);$config['outbound_transport']=(string)$probe['transport'];}
            $result=$resolver->resolve($config)->send($config,$mail);
        }catch(\Throwable $e){$result=array('success'=>false,'error'=>preg_replace('/[^a-z0-9_\-]/i','',$e->getMessage())?:'email_transport_failed','retryable'=>false);}
        if($this->registry&&(int)($options['delivery_id']??0)>0)(new EmailDeliveryEvidenceRepository($this->registry))->record((int)$options['delivery_id'],hash('sha256',(string)($options['dedupe_key']??$messageId)),$result);
        if($this->registry)(new EmailAccount($this->registry))->recordRuntimeHealth('outbound',!empty($result['success']),(string)($result['error']??''),(string)($result['transport']??$config['outbound_transport']??''));
        if($this->registry&&!empty($result['success'])&&(int)($options['channel_id']??0)>0&&(int)($options['chat_id']??0)>0)(new EmailThreadIndex($this->registry))->remember((int)$options['channel_id'],(int)$options['chat_id'],(int)($options['message_id']??0),$messageId);
        return $result;
    }
}
