<?php

namespace App\Middlewares;

use App\Core\Request;
use App\Core\Response;
use App\Models\CompanySubscription;
use App\Models\CompanySubscriptionUsage;

/**
 * SubscriptionMiddleware
 * Validates company subscription validity and request quotas before processing operations.
 */
class SubscriptionMiddleware
{
    public function handle(Request $request, Response $response): void
    {
        // 1. Get company ID (populated by AuthMiddleware)
        $companyId = $request->company_id ?? null;

        if (!$companyId) {
            $response->json(['error' => 'Unauthorized', 'message' => 'Company details not found in request Context'], 401);
            exit;
        }

        // Allow Company 1 (Intaleq admin/demo) to bypass limits temporarily or have unlimited
        if ($companyId === 1) {
            return;
        }

        // 2. Fetch active subscription
        $activeSub = CompanySubscription::findActiveByCompany($companyId);
        if (!$activeSub) {
            $response->json([
                'error' => 'Payment Required',
                'message' => 'This account does not have an active subscription or the current subscription has expired. Please subscribe to a plan to continue.'
            ], 402);
            exit;
        }

        // 3. Verify total requests limit
        $hasQuota = CompanySubscriptionUsage::hasRemainingLimit($companyId, 'request');
        if (!$hasQuota) {
            $response->json([
                'error' => 'Quota Exceeded',
                'message' => 'You have exceeded the monthly request quota for your plan (' . $activeSub['max_requests'] . ' requests). Please upgrade your subscription.'
            ], 403);
            exit;
        }
    }
}
