<?php

declare(strict_types=1);

namespace App\Core;

final class Auth
{
    public static function user(Request $request): ?array
    {
        $payload = Jwt::decode($request->bearerToken());
        if (!$payload || empty($payload['sub'])) {
            return null;
        }
        return Database::fetchOne('SELECT * FROM users WHERE id = :id LIMIT 1', ['id' => $payload['sub']]);
    }

    public static function requireUser(Request $request): array
    {
        $user = self::user($request);
        if (!$user) {
            Response::error('Não autenticado', 401);
            exit;
        }
        return $user;
    }

    public static function tokenMunicipality(Request $request): ?string
    {
        $payload = Jwt::decode($request->bearerToken());
        return $payload['municipality_id'] ?? null;
    }
}
