<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Module\Helpdesk\Service\DebitorCacheControl;
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;
}

$customerNo = trim((string) $request->query('customerNo', ''));
$customerName = trim((string) $request->query('customerName', ''));
$refreshRequested = DebitorCacheControl::parseRefreshFlag($request->query('refresh', ''));

if ($customerNo === '' || $customerName === '') {
    http_response_code(400);
    Router::json(['ok' => false, 'error' => 'missing_parameters']);

    return;
}

$sessionStore = app(SessionStoreInterface::class);
$session = $sessionStore->all();
$tenantScope = DebitorCacheControl::resolveTenantScope($session);
if ($refreshRequested) {
    DebitorCacheControl::invalidateDebitorCaches($sessionStore, $tenantScope, $customerNo, true);
}

$cacheKey = DebitorCacheControl::communicationKey($tenantScope, $customerNo);
$cacheTtl = DebitorCacheControl::TTL_STANDARD_SECONDS;
$cached = $sessionStore->get($cacheKey);
$cacheUsed = false;

if (!$refreshRequested && is_array($cached) && isset($cached['fetched_at']) && (time() - (int) $cached['fetched_at']) < $cacheTtl) {
    $cacheUsed = true;
    $payload = (array) ($cached['payload'] ?? ['ok' => false]);
    $meta = is_array($payload['meta'] ?? null) ? $payload['meta'] : [];
    $meta['cache_used'] = true;
    $meta['cache_bypassed'] = false;
    $meta['cache_refreshed'] = false;
    $payload['meta'] = $meta;
    Router::json($payload);

    return;
}

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

$meta = is_array($result['meta'] ?? null) ? $result['meta'] : [];
$meta['cache_used'] = $cacheUsed;
$meta['cache_bypassed'] = $refreshRequested;
$meta['cache_refreshed'] = $refreshRequested;
$result['meta'] = $meta;

Router::json($result);
