<?php

declare(strict_types=1);

namespace App\Middlewares;

use App\Helpers\Request;
use App\Models\UserSession;
use App\Models\User;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\ExpiredException;

class AuthMiddleware
{
    public function handle(Request $request): mixed
    {
        $token = $request->bearerToken();

        if (!$token) {
            return 'Token no proporcionado';
        }

        try {
            $config = require BASE_PATH . '/config/app.php';
            $decoded = JWT::decode($token, new Key($config['jwt']['secret'], 'HS256'));

            $sessionModel = new UserSession();
            $session = $sessionModel->findByToken($token);

            if (!$session) {
                return 'Sesión inválida o cerrada';
            }

            $userModel = new User();
            $user = $userModel->findById((int) $decoded->sub);

            $request->setRouteParams([
                'auth_user_id' => $decoded->sub,
                'auth_user_role' => $decoded->role,
                'auth_user_event_id' => $user['current_event_id'] ?? null,
            ]);

            return null;
        } catch (ExpiredException $e) {
            return 'Token expirado';
        } catch (\Exception $e) {
            return 'Token inválido';
        }
    }
}
