<?php

use App\Controllers\AuthController;
use App\Controllers\CatalogController;
use App\Controllers\ExportController;
use App\Controllers\MatchController;
use App\Controllers\MatchSheetController;
use App\Controllers\PlayerController;
use App\Controllers\PublicController;
use App\Controllers\ScoresheetExportController;
use App\Controllers\SheetTemplateController;
use App\Controllers\TeamController;
use App\Controllers\TournamentController;
use App\Controllers\UploadController;
use App\Controllers\UserController;
use App\Core\Log;
use App\Core\Response;
use App\Core\Router;

spl_autoload_register(function (string $class): void {
    $prefix = 'App\\';
    if (!str_starts_with($class, $prefix)) {
        return;
    }
    $path = __DIR__ . '/../app/' . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php';
    if (is_file($path)) {
        require $path;
    }
});

$config = require __DIR__ . '/../config/app.php';
header('Access-Control-Allow-Origin: ' . $config['cors_origin']);
header('Access-Control-Allow-Headers: Authorization, Content-Type');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit;
}

if (!str_starts_with(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?: '/', '/api')) {
    require __DIR__ . '/app.html';
    exit;
}

$router = new Router();
$router->add('POST', '/api/auth/login', [AuthController::class, 'login']);
$router->add('GET', '/api/auth/me', [AuthController::class, 'me']);
$router->add('GET', '/api/users', [UserController::class, 'index']);
$router->add('POST', '/api/users', [UserController::class, 'store']);
$router->add('PUT', '/api/users/{id}', [UserController::class, 'update']);
$router->add('GET', '/api/tournaments', [TournamentController::class, 'index']);
$router->add('POST', '/api/tournaments', [TournamentController::class, 'store']);
$router->add('POST', '/api/tournaments/{id}/fixture', [MatchController::class, 'generateFixture']);
$router->add('POST', '/api/tournaments/{id}/demo-scoresheet-data', [TournamentController::class, 'demoScoresheet']);
$router->add('GET', '/api/tournaments/{id}/standings', [PublicController::class, 'standings']);
$router->add('GET', '/api/tournaments/{id}/stats', [PublicController::class, 'stats']);
$router->add('GET', '/api/tournaments/{id}/export/csv', [ExportController::class, 'standingsCsv']);
$router->add('GET', '/api/tournaments/{id}/export/pdf', [ExportController::class, 'standingsPdf']);
$router->add('POST', '/api/tournaments/{id}/sheet-template', [SheetTemplateController::class, 'assignTournament']);
$router->add('GET', '/api/sheet-templates', [SheetTemplateController::class, 'index']);
$router->add('POST', '/api/sheet-templates', [SheetTemplateController::class, 'store']);
$router->add('GET', '/api/sheet-templates/{id}', [SheetTemplateController::class, 'show']);
$router->add('GET', '/api/sheet-templates/{id}/effective', [SheetTemplateController::class, 'effective']);
$router->add('PUT', '/api/sheet-templates/{id}', [SheetTemplateController::class, 'update']);
$router->add('GET', '/api/teams', [TeamController::class, 'index']);
$router->add('POST', '/api/teams', [TeamController::class, 'store']);
$router->add('GET', '/api/players', [PlayerController::class, 'index']);
$router->add('POST', '/api/players', [PlayerController::class, 'store']);
$router->add('POST', '/api/team-links/{token}/players', [PlayerController::class, 'registerByLink']);
$router->add('GET', '/api/matches', [MatchController::class, 'index']);
$router->add('POST', '/api/matches', [MatchController::class, 'store']);
$router->add('GET', '/api/matches/{id}/score', [MatchController::class, 'scoreState']);
$router->add('GET', '/api/matches/{id}/scoresheet/ltv26', [ScoresheetExportController::class, 'ltv26']);
$router->add('POST', '/api/matches/{id}/sheet-template', [SheetTemplateController::class, 'overrideMatch']);
$router->add('POST', '/api/matches/{id}/events', [MatchController::class, 'scoreEvent']);
$router->add('GET', '/api/matches/{id}/advanced-score', [MatchController::class, 'advancedState']);
$router->add('GET', '/api/matches/{id}/sheet-details', [MatchSheetController::class, 'index']);
$router->add('POST', '/api/matches/{id}/sheet-details', [MatchSheetController::class, 'save']);
$router->add('POST', '/api/matches/{id}/rotations', [MatchController::class, 'rotation']);
$router->add('POST', '/api/matches/{id}/liberos', [MatchController::class, 'libero']);
$router->add('POST', '/api/matches/{id}/substitutions', [MatchController::class, 'substitution']);
$router->add('POST', '/api/matches/{id}/timeouts', [MatchController::class, 'timeout']);
$router->add('POST', '/api/matches/{id}/rallies', [MatchController::class, 'rally']);
$router->add('POST', '/api/matches/{id}/advanced-sanctions', [MatchController::class, 'advancedSanction']);
$router->add('POST', '/api/matches/{id}/signatures', [MatchController::class, 'signature']);
$router->add('POST', '/api/matches/{id}/sanctions', [CatalogController::class, 'sanction']);
$router->add('GET', '/api/courts', [CatalogController::class, 'courts']);
$router->add('GET', '/api/referees', [CatalogController::class, 'referees']);
$router->add('POST', '/api/uploads/images', [UploadController::class, 'image']);

try {
    $router->dispatch($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);
} catch (Throwable $e) {
    Log::error($e->getMessage(), ['trace' => $config['debug'] ? $e->getTraceAsString() : null]);
    Response::error($config['debug'] ? $e->getMessage() : 'Error interno', 500);
}
