<?php
namespace EasyChat\Library\Email;

final class EmailDeliveryEvidenceRepository {
    private $db;
    private $prefix;
    public function __construct($registry) { $this->db=$registry->get('db');$this->prefix=easychat_db_prefix(); }
    public function record(int $deliveryId,string $idempotencyKey,array $result): void {
        if($deliveryId<=0||$idempotencyKey==='')return;
        $transport=preg_replace('/[^a-z0-9_\-]/i','',(string)($result['transport']??'unknown'));
        $providerId=mb_substr(trim((string)($result['provider_message_id']??$result['external_message_id']??'')),0,128);
        $status=mb_substr(trim((string)($result['delivery_state']??(!empty($result['success'])?'accepted':'failed'))),0,32);
        $certainty=!empty($result['outcome_unknown'])?'unknown':'known';
        $evidence=array('http_code'=>(int)($result['http_code']??0),'error'=>mb_substr((string)($result['error']??''),0,120));
        $this->db->query("INSERT INTO `{$this->prefix}email_delivery_evidence` SET `delivery_id`={$deliveryId},`transport_code`='".$this->db->escape($transport)."',`idempotency_key`='".$this->db->escape($idempotencyKey)."',`provider_message_id`='".$this->db->escape($providerId)."',`provider_status`='".$this->db->escape($status)."',`outcome_certainty`='{$certainty}',`evidence_json`='".$this->db->escape(json_encode($evidence,JSON_UNESCAPED_SLASHES))."',`last_checked_at`=NOW(),`date_modified`=NOW() ON DUPLICATE KEY UPDATE `transport_code`=VALUES(`transport_code`),`provider_message_id`=VALUES(`provider_message_id`),`provider_status`=VALUES(`provider_status`),`outcome_certainty`=VALUES(`outcome_certainty`),`evidence_json`=VALUES(`evidence_json`),`last_checked_at`=NOW(),`date_modified`=NOW()");
    }
}
