<?php

namespace Middlewares;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Libs\ResponseLib;
use Psr\Http\Message\ServerRequestInterface;

class JwtAuthMiddleware
{
    private string $jwtSecret;

    public function __construct()
    {
        // Carrega a chave secreta do .env (ex: JWT_SECRET=seu-segredo-aqui)
        $this->jwtSecret = $_ENV['JWT_SECRET'] ?? 'default-secret-fallback';  // Use um fallback seguro em dev
    }

    public function __invoke(ServerRequestInterface $request, callable $next)
    {
        $authHeader = $request->getHeaderLine('Authorization');
        if (empty($authHeader) || !preg_match('/Bearer\s+(.*)/', $authHeader, $matches)) {
            return ResponseLib::sendFail("Unauthorized: Missing or invalid Authorization header", [], "E_VALIDATE")->withStatus(401);
        }

        $token = $matches[1];

        try {
            $decoded = JWT::decode($token, new Key($this->jwtSecret, 'HS256'));
            $userId = $decoded->sub ?? null;
            $email = $decoded->email ?? null;

            if (empty($userId) || empty($email)) {
                return ResponseLib::sendFail("Unauthorized: Invalid JWT claims", [], "E_VALIDATE")->withStatus(401);
            }

            if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof \PDO) {
                $pdo = $GLOBALS['pdo'];
            }
            
            $stmt = $pdo->prepare('SELECT user_id, company_id FROM "user" WHERE user_id = :user_id AND user_email = :email AND user_flag = \'a\'');
            $stmt->execute(['user_id' => $userId, 'email' => $email]);
            $user = $stmt->fetch(\PDO::FETCH_ASSOC);

            if (!$user) {
                return ResponseLib::sendFail("Unauthorized: Invalid or inactive user", [], "E_VALIDATE")->withStatus(401);
            }

            $request = $request
                ->withAttribute('api_user', $email)
                ->withAttribute('api_user_id', $userId)
                ->withAttribute('api_company_id', $user['company_id']);

            $GLOBALS['api_user_id'] = (int)$userId;
            $GLOBALS['api_company_id'] = (int)$user['company_id'];

            return $next($request);

        } catch (\Exception $e) {
            return ResponseLib::sendFail("Unauthorized: " . $e->getMessage(), [], "E_VALIDATE")->withStatus(401);
        }
    }
}