<?php

declare(strict_types=1);

use GalpaoImperial\Api\Database;
use GalpaoImperial\Api\HttpException;
use GalpaoImperial\Api\SiteRepository;
use function GalpaoImperial\Api\corsPreflight;
use function GalpaoImperial\Api\jsonBody;
use function GalpaoImperial\Api\jsonResponse;
use function GalpaoImperial\Api\required;

corsPreflight($method);
$repository = new SiteRepository(Database::connection());
$type = $segments[1] ?? '';
$action = $segments[2] ?? '';

if ($type === 'ticket' && $method === 'POST' && $action === 'search') {
    $payload = jsonBody();
    required($payload, ['query']);
    $eventId = isset($payload['eventId']) && ctype_digit((string) $payload['eventId']) ? (int) $payload['eventId'] : null;
    jsonResponse(['success' => true, 'data' => $repository->findTicketValidation((string) $payload['query'], $eventId)]);
}

if ($type === 'ticket' && $method === 'POST' && $action === 'list') {
    $payload = jsonBody();
    $eventId = isset($payload['eventId']) && ctype_digit((string) $payload['eventId']) ? (int) $payload['eventId'] : null;
    $limit = isset($payload['limit']) && ctype_digit((string) $payload['limit']) ? (int) $payload['limit'] : 80;
    $activeOnly = !array_key_exists('activeOnly', $payload) || (bool) $payload['activeOnly'];
    jsonResponse(['success' => true, 'data' => $repository->listTicketValidation((string) ($payload['query'] ?? ''), $eventId, $limit, $activeOnly)]);
}

if ($type === 'ticket' && $method === 'POST' && $action === 'check-in') {
    $payload = jsonBody();
    required($payload, ['ticketCode']);
    $eventId = isset($payload['eventId']) && ctype_digit((string) $payload['eventId']) ? (int) $payload['eventId'] : null;
    jsonResponse(['success' => true, 'data' => $repository->checkInTicket((string) $payload['ticketCode'], (string) ($payload['validatedBy'] ?? 'Portaria'), $eventId)]);
}

if ($type === 'partner' && $method === 'POST' && $action === 'search') {
    $payload = jsonBody();
    required($payload, ['query']);
    jsonResponse(['success' => true, 'data' => $repository->findPartnerValidation((string) $payload['query'])]);
}

if ($type === 'partner' && $method === 'POST' && $action === 'check') {
    $payload = jsonBody();
    required($payload, ['query']);
    jsonResponse(['success' => true, 'data' => $repository->validatePartner((string) $payload['query'], (string) ($payload['validatedBy'] ?? 'Portaria'))]);
}

if ($type === 'gift' && $method === 'POST' && $action === 'search') {
    $payload = jsonBody();
    required($payload, ['query']);
    jsonResponse(['success' => true, 'data' => $repository->findGiftClaim((string) $payload['query'])]);
}

if ($type === 'gift' && $method === 'POST' && $action === 'use') {
    $payload = jsonBody();
    required($payload, ['id']);
    jsonResponse(['success' => true, 'data' => $repository->useGiftClaim((int) $payload['id'])]);
}

throw new HttpException(404, 'Validador não encontrado.');
