<?php

namespace App\Middlewares;

use App\Core\Request;
use App\Core\Response;
use App\Core\Security;

class AuthMiddleware
{
    /**
     * Verifies the JWT token and populates request properties.
     */
    public function handle(Request $request, Response $response): void
    {
        $authHeader = $request->getHeader('authorization', '');

        if (!$authHeader || !preg_match('/Bearer\s(\S+)/i', $authHeader, $matches)) {
            $response->json(['error' => 'Unauthorized', 'message' => 'Token not provided or invalid format'], 401);
            exit;
        }

        $token = $matches[1];
        $payload = Security::verifyJWT($token);

        if (!$payload) {
            $response->json(['error' => 'Unauthorized', 'message' => 'Invalid or expired token'], 401);
            exit;
        }

        // Validate required custom payload elements
        if (!isset($payload['user_id']) || !isset($payload['company_id']) || !isset($payload['role'])) {
            $response->json(['error' => 'Unauthorized', 'message' => 'Malformed token payload structure'], 401);
            exit;
        }

        // Attach user info to the Request instance dynamically so controllers can use it
        $request->user_id = $payload['user_id'];
        $request->company_id = $payload['company_id'];
        $request->role = $payload['role'];
        $request->is_super_admin = (int)$payload['company_id'] === 1;
    }
}
