<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Module\Helpdesk\Service\TicketCommunicationService;
use MintyPHP\Router;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requireAbilityOrForbidden(HelpdeskAuthorizationPolicy::ABILITY_ACCESS);

$request = requestInput();
if ($request->method() !== 'GET') {
    http_response_code(405);
    Router::json(['ok' => false, 'error' => 'method_not_allowed']);

    return;
}

$ticketNo = trim((string) $request->query('ticketNo', ''));
if ($ticketNo === '') {
    http_response_code(400);
    Router::json(['ok' => false, 'error' => 'missing_parameters']);

    return;
}

$sessionStore = app(SessionStoreInterface::class);
$session = $sessionStore->all();
$tenantId = (int) (($session['current_tenant']['id'] ?? 0));
$tenantScope = $tenantId > 0 ? (string) $tenantId : 'global';
$cacheKey = 'module.helpdesk.ticket_comm_cache.v2.' . $tenantScope . '.' . $ticketNo;
$cacheTtl = 120;
$cached = $sessionStore->get($cacheKey);

if (is_array($cached) && isset($cached['fetched_at']) && (time() - (int) $cached['fetched_at']) < $cacheTtl) {
    Router::json((array) ($cached['payload'] ?? ['ok' => false]));

    return;
}

$service = app(TicketCommunicationService::class);
$result = $service->loadTicketCommunicationFeed($ticketNo, 40);
if (($result['ok'] ?? false) === true) {
    $sessionStore->set($cacheKey, [
        'payload' => $result,
        'fetched_at' => time(),
    ]);
}

Router::json($result);
