<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Module\Helpdesk\Service\DebitorCacheControl;
use MintyPHP\Module\Helpdesk\Service\DebitorDetailService;
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::contractLinesKey($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 = is_array($cached['payload'] ?? null) ? $cached['payload'] : ['ok' => false];
    $payload['meta'] = [
        'cache_used' => true,
        'cache_bypassed' => false,
        'cache_refreshed' => false,
    ];
    Router::json($payload);

    return;
}

$service = app(DebitorDetailService::class);
$result = $service->loadSalesDashboard($customerNo, $customerName);

if (($result['ok'] ?? false) === true) {
    $sessionStore->set($cacheKey, [
        'payload' => $result,
        'fetched_at' => time(),
    ]);
}

$result['meta'] = [
    'cache_used' => $cacheUsed,
    'cache_bypassed' => $refreshRequested,
    'cache_refreshed' => $refreshRequested,
];

Router::json($result);
