<?php

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

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

$request = requestInput();
$body = $request->bodyAll();

// CSRF: Router skips automatic check for AJAX (X-Requested-With header).
// For non-AJAX POST, verify manually.
if ($request->isMethod('POST') && empty($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    if (!Session::checkCsrfToken()) {
        Router::json(['ok' => false, 'errors' => ['general' => 'Invalid CSRF token']]);

        return;
    }
}

$session = app(SessionStoreInterface::class)->all();
$tenantId = (int) ($session['current_tenant']['id'] ?? 0);
$userId = (int) ($session['user']['id'] ?? 0);

$service = app(UpdateService::class);
$result = $service->assignUpdate(
    $tenantId,
    (string) ($body['ticket_no'] ?? ''),
    (string) ($body['debitor_no'] ?? ''),
    (string) ($body['debitor_name'] ?? ''),
    (string) ($body['category_code'] ?? ''),
    (string) ($body['domain_no'] ?? ''),
    (string) ($body['domain_url'] ?? ''),
    (string) ($body['gitea_path'] ?? ''),
    (string) ($body['notes'] ?? ''),
    $userId
);

Router::json($result);
