<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Module\Helpdesk\Service\BcODataGateway;
use MintyPHP\Module\Helpdesk\Service\DebitorCacheControl;
use MintyPHP\Module\Helpdesk\Service\DebitorDetailService;
use MintyPHP\Module\Helpdesk\Service\HelpdeskSettingsGateway;
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', ''));
$periodDays = (int) $request->query('periodDays', '90');
$refreshRequested = DebitorCacheControl::parseRefreshFlag($request->query('refresh', ''));

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

    return;
}

$allowedPeriods = [30, 90, 180, 365];
if (!in_array($periodDays, $allowedPeriods, true)) {
    $periodDays = 90;
}

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

// --- Load controlling tickets (period-independent cache: full 500 tickets) ---

$ticketsCacheKey = DebitorCacheControl::controllingTicketsKey($tenantScope, $customerNo);
$cacheTtl = DebitorCacheControl::TTL_STANDARD_SECONDS;
$cached = $sessionStore->get($ticketsCacheKey);
$tickets = null;
$ticketsCacheUsed = false;

if (!$refreshRequested && is_array($cached) && isset($cached['fetched_at']) && (time() - (int) $cached['fetched_at']) < $cacheTtl) {
    $tickets = is_array($cached['tickets'] ?? null) ? $cached['tickets'] : [];
    $ticketsCacheUsed = true;
}

if ($tickets === null) {
    $gateway = app(BcODataGateway::class);

    try {
        $tickets = $gateway->getTicketsForControlling($customerNo);
    } catch (\Throwable $e) {
        Router::json([
            'ok' => false,
            'error' => 'Failed to load controlling tickets: ' . $e->getMessage(),
        ]);

        return;
    }

    if (!is_array($tickets)) {
        $tickets = [];
    }

    $sessionStore->set($ticketsCacheKey, [
        'tickets' => $tickets,
        'fetched_at' => time(),
    ]);
}

// --- Load contract data (reuse existing contracts cache from Sales tab) ---

// --- Load risk config ---

$settingsGateway = app(HelpdeskSettingsGateway::class);
$riskConfig = $settingsGateway->getControllingRiskConfig();

// --- Build dashboard ---

$dashboard = DebitorDetailService::buildControllingDashboard(
    $tickets,
    $periodDays,
    $riskConfig
);

Router::json([
    'ok' => true,
    'kpis' => $dashboard['kpis'],
    'trend' => $dashboard['trend'],
    'risk_indicators' => $dashboard['risk_indicators'],
    'meta' => array_merge($dashboard['meta'], [
        'cache_used' => $ticketsCacheUsed,
        'cache_bypassed' => $refreshRequested,
        'cache_refreshed' => $refreshRequested,
    ]),
]);
