<?php
namespace EasyChat\Library\Queue\Jobs;

use EasyChat\Library\Catalog\CatalogCanonicalProbe;
use EasyChat\Library\Catalog\CatalogPublicUrlService;
use EasyChat\Library\Queue\JobInterface;

class CatalogUrlVerifyJob implements JobInterface {

    private $registry;

    public function __construct($registry) {
        $this->registry = $registry;
    }

    public function handle(array $payload): void {
        $items = is_array($payload['items'] ?? null) ? array_slice($payload['items'], 0, 20) : array();
        if (!$items) {
            return;
        }
        $db = $this->registry->get('db');
        $prefix = easychat_db_prefix();
        $probe = new CatalogCanonicalProbe($this->registry);
        $now = time();

        foreach ($items as $item) {
            $cache_key = strtolower(trim((string)($item['cache_key'] ?? '')));
            $source_url = trim((string)($item['source_url'] ?? ''));
            $source_hash = strtolower(trim((string)($item['source_hash'] ?? '')));
            $origin = trim((string)($item['origin'] ?? ''));
            if (!preg_match('/^[a-f0-9]{64}$/', $cache_key)
                || !preg_match('/^[a-f0-9]{64}$/', $source_hash)) {
                continue;
            }

            $result = $probe->probe($source_url, $origin);
            $status = (string)($result['status'] ?? 'failed') === 'verified' ? 'verified' : 'failed';
            $canonical = $status === 'verified' ? (string)($result['canonical_url'] ?? '') : '';
            $http_code = max(0, min(65535, (int)($result['http_code'] ?? 0)));
            $error_code = preg_replace('/[^a-z0-9_-]/', '', strtolower((string)($result['error_code'] ?? 'probe_failed')));
            $expires_at = $now + ($status === 'verified' ? CatalogPublicUrlService::VERIFIED_TTL : CatalogPublicUrlService::FAILED_TTL);

             
             
            $db->query(
                "UPDATE `{$prefix}catalog_url_cache`
                 SET canonical_url = '" . $db->escape($canonical) . "',
                     status = '" . $db->escape($status) . "',
                     http_code = {$http_code}, error_code = '" . $db->escape($error_code) . "',
                     checked_at = {$now}, expires_at = {$expires_at}
                 WHERE cache_key = '" . $db->escape($cache_key) . "'
                   AND source_hash = '" . $db->escape($source_hash) . "'"
            );
        }
    }
}
