<?php

namespace App\Http\Middleware;

use App\Services\Growth\QuotaService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class FeatureGuard
{
    public function handle(Request $request, Closure $next, string $feature): Response
    {
        $userId = optional($request->user())->id ?? 0; // TODO: replace with auth or tg mapping
        $period = match ($feature) {
            'instant_push' => 'day',
            'pricecheck' => 'month',
            'view_deals' => 'day',
            default => 'month',
        };
        $quotaKey = match ($feature) {
            'instant_push' => 'instant_push_per_day',
            'pricecheck' => 'valuations_per_month',
            'view_deals' => 'view_deals',
            default => 'valuations_per_month',
        };

        $ok = app(QuotaService::class)->checkAndConsume($userId, $quotaKey, $period);
        if (!$ok) {
            return response()->json([
                'error' => 'forbidden',
                'code' => 'UPSELL_LIMIT',
                'title' => 'Upgrade Required',
                'message' => 'You have reached your plan limit for this feature.',
                'quota' => $quotaKey,
                'remaining' => 0,
                'upgrade_url' => '/payments/create',
            ], 403);
        }
        return $next($request);
    }
}
