<?php
namespace EasyChat\Library\Chat;

use EasyChat\Library\Queue\Jobs\ChatAttachmentCleanupJob;
use EasyChat\Library\Queue\QueueManager;
use EasyChat\Model\Session;
use EasyChat\Model\ScheduledMessage;








class ChatDeletionService {
    private $registry;
    private $db;

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

    public function delete(array $chat_ids): array {
        $chat_ids = array_values(array_unique(array_filter(array_map('intval', $chat_ids))));
        if (!$chat_ids) {
            return ['success' => true, 'deleted_chat_ids' => [], 'cleanup_queued' => 0];
        }
        sort($chat_ids, SORT_NUMERIC);

         
         
        $queue = new QueueManager($this->registry);
        $cleanup_job_ids = [];
        $session = new Session($this->registry);
        $deleted_chat_ids = [];

        try {
            $this->db->query('START TRANSACTION');
            $deleted_chat_ids = $session->lockChatIdsForDeletion($chat_ids);
            if ($deleted_chat_ids) {
                 
                (new ScheduledMessage($this->registry))->cancelForChats($deleted_chat_ids);
            }
            $session->deleteSessions($deleted_chat_ids);
            foreach (array_chunk($deleted_chat_ids, 100) as $batch) {
                $cleanup_job_ids[] = $queue->pushUnique(
                    'chat_attachment_cleanup',
                    ['chat_ids' => $batch],
                    'chat_attachment_cleanup:' . hash('sha256', implode(',', $batch)),
                    0,
                    20
                );
            }
            $this->db->query('COMMIT');
        } catch (\Throwable $e) {
            try {
                $this->db->query('ROLLBACK');
            } catch (\Throwable $ignored) {
            }
            return ['success' => false, 'error' => 'chat_delete_failed', 'http_code' => 409];
        }

        $this->runCleanupJobs($queue, $cleanup_job_ids);
        return [
            'success' => true,
            'deleted_chat_ids' => $deleted_chat_ids,
            'cleanup_queued' => count($cleanup_job_ids),
        ];
    }

    private function runCleanupJobs(QueueManager $queue, array $job_ids): void {
        try {
            $handler = new ChatAttachmentCleanupJob($this->registry);
            foreach ($job_ids as $job_id) {
                $claimed = $queue->claimById((int)$job_id);
                if (!$claimed) continue;
                $lock_token = (string)($claimed['lock_token'] ?? '');
                $payload = json_decode((string)($claimed['payload'] ?? ''), true);
                try {
                    if (!is_array($payload)) {
                        throw new \RuntimeException('chat_attachment_cleanup_payload_invalid');
                    }
                    $handler->handle($payload);
                    $queue->markDone((int)$job_id, $lock_token);
                } catch (\Throwable $e) {
                    $queue->reschedule((int)$job_id, 30, 'chat_attachment_cleanup_retry', $lock_token);
                }
            }
        } catch (\Throwable $e) {
             
             
        }
    }
}
