<?php

declare(strict_types=1);

namespace App\Helpers;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\ExpiredException;

class Session
{
    private static ?array $currentUser = null;

    public static function generateToken(array $user, int $expirationSeconds = 28800): string
    {
        $config = require BASE_PATH . '/config/app.php';
        $now = time();

        $payload = [
            'iss' => $config['app']['url'],
            'iat' => $now,
            'exp' => $now + ($expirationSeconds ?: (int) $config['jwt']['expiration']),
            'sub' => $user['id'],
            'role' => $user['role'],
            'event_id' => $user['current_event_id'] ?? null,
        ];

        return JWT::encode($payload, $config['jwt']['secret'], 'HS256');
    }

    public static function decodeToken(string $token): ?array
    {
        $config = require BASE_PATH . '/config/app.php';

        try {
            $decoded = JWT::decode($token, new Key($config['jwt']['secret'], 'HS256'));
            return (array) $decoded;
        } catch (ExpiredException $e) {
            return null;
        } catch (\Exception $e) {
            return null;
        }
    }

    public static function setUser(array $user): void
    {
        self::$currentUser = $user;
    }

    public static function user(): ?array
    {
        return self::$currentUser;
    }

    public static function userId(): ?int
    {
        return self::$currentUser['sub'] ?? null;
    }

    public static function userRole(): ?string
    {
        return self::$currentUser['role'] ?? null;
    }

    public static function userEventId(): ?int
    {
        $id = self::$currentUser['event_id'] ?? null;
        return $id ? (int) $id : null;
    }

    public static function isAuthenticated(): bool
    {
        return self::$currentUser !== null;
    }

    public static function isSuperAdmin(): bool
    {
        return self::userRole() === 'super_admin';
    }

    public static function isComercialManager(): bool
    {
        return self::userRole() === 'comercial_manager';
    }

    public static function refreshToken(string $token): ?string
    {
        $decoded = self::decodeToken($token);
        if (!$decoded) {
            return null;
        }

        return self::generateToken([
            'id' => $decoded['sub'],
            'role' => $decoded['role'],
            'current_event_id' => $decoded['event_id'] ?? null,
        ]);
    }

    public static function clear(): void
    {
        self::$currentUser = null;
    }
}
