<?php

namespace App\Http\Middleware;

use App\Models\Website;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\Response;

class RateLimitApiRequests
{
    public function handle(Request $request, Closure $next): Response
    {
        $website = $request->user();

        if (!$website instanceof Website) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }

        if (!$website->is_active) {
            return response()->json(['message' => 'Account inactive'], 403);
        }

        if (app()->environment('local') || $website->bypass_rate_limit) {
            return $next($request);
        }

        if (!$this->originMatchesDomain($request, $website)) {
            return response()->json(['message' => 'Forbidden'], 403);
        }

        $hour = now()->format('Y-m-d-H');
        $cacheKey = "rate_limit:website:{$website->id}:cache_hits:{$hour}";
        $attempts = Cache::get($cacheKey, 0);

        if ($attempts >= $website->cache_hit_rate_limit) {
            return response()->json([
                'message' => 'Rate limit exceeded',
                'limit' => $website->cache_hit_rate_limit,
                'reset_at' => now()->addHour()->startOfHour()->timestamp,
            ], 429);
        }

        $request->attributes->set('rate_limit_key', $cacheKey);

        $response = $next($request);


        $response->headers->set('X-RateLimit-Limit', $website->cache_hit_rate_limit);
        $response->headers->set('X-RateLimit-Remaining', max(0, $website->cache_hit_rate_limit - $attempts - 1));
        $response->headers->set('X-RateLimit-Reset', now()->addHour()->startOfHour()->timestamp);

        return $response;
    }

    private function originMatchesDomain(Request $request, Website $website): bool
    {
        $origin = $request->header('Origin') ?? $request->header('Referer');

        if (!$origin) {
            return false;
        }

        $host = parse_url($origin, PHP_URL_HOST);

        return $host === $website->domain;
    }
}
