<?php

declare(strict_types=1);

use GalpaoImperial\Api\HttpException;
use function GalpaoImperial\Api\adminIsAuthenticated;
use function GalpaoImperial\Api\corsPreflight;
use function GalpaoImperial\Api\jsonBody;
use function GalpaoImperial\Api\jsonResponse;
use function GalpaoImperial\Api\performAdminLogin;
use function GalpaoImperial\Api\performAdminLogout;
use function GalpaoImperial\Api\required;

corsPreflight($method);
$action = $segments[1] ?? 'me';

if ($method === 'GET' && $action === 'me') {
    jsonResponse([
        'success' => true,
        'data' => [
            'authenticated' => adminIsAuthenticated(),
            'username' => $_SESSION['admin_username'] ?? null,
        ],
    ]);
}

if ($method === 'POST' && $action === 'login') {
    $payload = jsonBody();
    required($payload, ['username', 'password']);

    $ok = performAdminLogin((string) $payload['username'], (string) $payload['password']);
    if (!$ok) {
        throw new HttpException(401, 'Usuário ou senha inválidos.');
    }

    jsonResponse([
        'success' => true,
        'data' => [
            'authenticated' => true,
            'username' => $_SESSION['admin_username'] ?? null,
        ],
    ]);
}

if ($method === 'POST' && $action === 'logout') {
    performAdminLogout();
    jsonResponse([
        'success' => true,
        'data' => [
            'authenticated' => false,
        ],
    ]);
}

throw new HttpException(404, 'Rota de autenticação não encontrada.');
