<?php
declare(strict_types=1);
require_once __DIR__ . '/../../src/bootstrap.php';

if (!Auth::user()) {
    json_out(['ok' => false, 'error' => 'unauthorized'], 401);
}

try {
    Database::requireTicketsTable();
} catch (RuntimeException $e) {
    json_out(['ok' => false, 'error' => 'tickets_table_missing', 'hint' => $e->getMessage()], 503);
}

$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
$id = (int) ($_GET['id'] ?? 0);

if ($method === 'GET') {
    if ($id <= 0) {
        json_out(['ok' => false, 'error' => 'invalid id'], 400);
    }
    $ticket = TicketRepository::getById($id);
    if (!$ticket) {
        json_out(['ok' => false, 'error' => 'not found'], 404);
    }
    json_out([
        'ok' => true,
        'id' => $id,
        'tags' => $ticket['tags'] ?? [],
        'presets' => TicketRepository::listTagPresets(),
        'can_edit' => !empty($ticket['can_edit']),
    ]);
}

if ($method !== 'PUT' && $method !== 'POST') {
    json_out(['ok' => false, 'error' => 'method not allowed'], 405);
}

$raw = file_get_contents('php://input');
$data = is_string($raw) && $raw !== '' ? json_decode($raw, true) : $_POST;
if (!is_array($data)) {
    json_out(['ok' => false, 'error' => 'invalid json'], 400);
}
$id = (int) ($data['id'] ?? $id);
if ($id <= 0) {
    json_out(['ok' => false, 'error' => 'invalid id'], 400);
}

$ticket = TicketRepository::getById($id);
if (!$ticket) {
    json_out(['ok' => false, 'error' => 'not found'], 404);
}
if (empty($ticket['can_edit'])) {
    json_out(['ok' => false, 'error' => 'forbidden'], 403);
}

$tagsIn = $data['tags'] ?? [];
if (!is_array($tagsIn)) {
    json_out(['ok' => false, 'error' => 'tags must be array'], 400);
}

try {
    TicketRepository::setCustomTags($id, $tagsIn);
    $updated = TicketRepository::getById($id);
    json_out([
        'ok' => true,
        'id' => $id,
        'tags' => $updated['tags'] ?? [],
    ]);
} catch (InvalidArgumentException $e) {
    json_out(['ok' => false, 'error' => $e->getMessage()], 400);
} catch (Throwable $e) {
    error_log('ticket_tags: ' . $e->getMessage());
    json_out(['ok' => false, 'error' => 'save failed'], 500);
}
