<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Module\Helpdesk\Service\DomainSecurityLevelService;
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

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

$request = requestInput();
$session = app(SessionStoreInterface::class)->all();
$tenantId = (int) ($session['current_tenant']['id'] ?? 0);
$userId = (int) ($session['user']['id'] ?? 0);
$service = app(DomainSecurityLevelService::class);
$isPost = $request->isMethod('POST');
$wantsJson = $request->wantsJson();

$domainNo = trim((string) ($isPost
    ? $request->body('domain_no', '')
    : $request->query('domain_no', '')));

$redirectUrl = $domainNo !== ''
    ? 'helpdesk/domain/' . rawurlencode($domainNo)
    : 'helpdesk/domains';

$fail = static function (string $error, int $status = 400) use ($wantsJson, $redirectUrl): void {
    if ($wantsJson) {
        http_response_code($status);
        Router::json(['ok' => false, 'error' => $error]);
        return;
    }
    Flash::error(t($error), 'helpdesk-domains', 'security_level_error');
    Router::redirect($redirectUrl);
};

if ($tenantId <= 0) {
    $fail('No tenant context', 400);
    return;
}

if ($domainNo === '') {
    $fail('Missing domain number', 400);
    return;
}

if (!$isPost) {
    $details = $service->getDetails($tenantId, $domainNo);
    Router::json([
        'ok' => true,
        'level' => $details['level'],
        'badge_variant' => DomainSecurityLevelService::getBadgeVariant($details['level']),
        'note' => $details['note'],
    ]);
    return;
}

if (!Session::checkCsrfToken()) {
    $fail('Invalid CSRF token', 403);
    return;
}

$level = trim((string) $request->body('security_level', ''));
if (!in_array($level, DomainSecurityLevelService::getAllowedLevels(), true)) {
    $fail('Invalid security level', 422);
    return;
}

$note = trim((string) $request->body('note', ''));

if (!$service->setLevel($tenantId, $domainNo, $level, $userId > 0 ? $userId : null, $note !== '' ? $note : null)) {
    $fail('Failed to save security level', 500);
    return;
}

if ($wantsJson) {
    Router::json([
        'ok' => true,
        'level' => $level,
        'badge_variant' => DomainSecurityLevelService::getBadgeVariant($level),
        'note' => $note,
    ]);
    return;
}

Flash::success(t('Security level updated'), 'helpdesk-domains', 'security_level_saved');
Router::redirect($redirectUrl);
