<?php
namespace EasyChat\Library\Email;

final class EmailThreadIndex {
    private $db;
    private $prefix;
    public function __construct($registry){$this->db=$registry->get('db');$this->prefix=easychat_db_prefix();}
    public function findChat(int $channelId,array $messageIds): int {
        foreach($this->normalizeMany($messageIds) as $mailId){$hash=hash('sha256',$mailId);$q=$this->db->query("SELECT `chat_id` FROM `{$this->prefix}email_thread_index` WHERE `channel_id`={$channelId} AND `mail_message_hash`='".$this->db->escape($hash)."' LIMIT 1");if($q&&$q->row)return (int)$q->row['chat_id'];}
        return 0;
    }
    public function remember(int $channelId,int $chatId,int $messageId,string $mailMessageId): void {
        $mailMessageId=$this->normalize($mailMessageId);if($channelId<=0||$chatId<=0||$mailMessageId==='')return;$hash=hash('sha256',$mailMessageId);
        $this->db->query("INSERT IGNORE INTO `{$this->prefix}email_thread_index` SET `channel_id`={$channelId},`chat_id`={$chatId},`message_id`=".($messageId>0?$messageId:'NULL').",`mail_message_id`='".$this->db->escape($mailMessageId)."',`mail_message_hash`='".$this->db->escape($hash)."',`date_added`=NOW()");
    }
    public function parseReferences(string $value): array {
        preg_match_all('/<([^<>\r\n]{1,512})>/', $value, $matches);
        return $this->normalizeMany((array)($matches[1]??array()));
    }
    private function normalizeMany(array $ids): array {return array_values(array_unique(array_filter(array_map(array($this,'normalize'),$ids))));}
    private function normalize(string $value): string {$value=strtolower(trim($value,"<> \t\r\n"));return $value!==''&&strlen($value)<=512&&!preg_match('/[\r\n<>]/',$value)?$value:'';}
}
