<?php

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

Guard::requireLogin();

if (!Session::checkCsrfToken()) {
    Router::json(['ok' => false, 'error' => 'csrf_expired']);

    return;
}

$action = strtolower(trim((string) ($action ?? '')));
$allowedActions = ['delete'];
if (!in_array($action, $allowedActions, true)) {
    Router::json(['ok' => false, 'error' => 'invalid_action']);

    return;
}

Guard::requireAbilityOrForbidden(HelpdeskAuthorizationPolicy::ABILITY_HANDOVERS_MANAGE);

$raw = requestInput()->bodyAll()['ids'] ?? '';
$ids = [];
if (is_array($raw)) {
    $ids = array_map('intval', $raw);
} elseif (is_string($raw)) {
    $ids = array_map('intval', array_filter(array_map('trim', explode(',', $raw))));
}
$ids = array_values(array_unique(array_filter($ids, static fn (int $id): bool => $id > 0)));

if ($ids === []) {
    Router::json(['ok' => false, 'error' => 'no_selection']);

    return;
}

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

$result = $service->deleteByIds($tenantId, $ids, HandoverService::PERMISSION_MANAGE);
Router::json($result);
