<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Enforces subscription validity on every API request.
 *
 * Rules:
 *  - super_admin → bypass always
 *  - inactive tenant (expired or suspended) → 402 Payment Required
 *
 * This runs AFTER TenantMiddleware so the tenant is already loaded.
 */
class SubscriptionMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        // super_admin bypasses all subscription checks
        if ($user->isSuperAdmin()) {
            return $next($request);
        }

        $tenant = $user->tenant;

        if (!$tenant) {
            return response()->json(['error' => 'No tenant found.'], 403);
        }

        // Suspended
        if ($tenant->isSuspended()) {
            return response()->json([
                'error'   => 'Subscription expired or inactive',
                'reason'  => 'suspended',
                'message' => 'Your account has been suspended. Please contact support.',
            ], 402);
        }

        // Expired
        if ($tenant->isExpired()) {
            // Auto-update status in DB
            $tenant->update(['status' => 'expired']);

            return response()->json([
                'error'   => 'Subscription expired or inactive',
                'reason'  => 'expired',
                'message' => 'Your subscription has expired. Please renew to continue.',
            ], 402);
        }

        return $next($request);
    }
}
