<?php

namespace App\Http\Middleware;

use App\Models\Tenant;
use App\Models\User;
use App\Services\Packages\PackageLimitEvaluator;
use App\Support\ApiError;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CreditCheckMiddleware
{
    public function __construct(private readonly PackageLimitEvaluator $limitEvaluator) {}

    public function handle(Request $request, Closure $next): Response
    {
        $tenant = $request->attributes->get('tenant');
        if (! $tenant instanceof Tenant) {
            $tenant = $this->resolveTenant($request);
            $request->attributes->set('tenant', $tenant);
            $request->attributes->set('tenant_id', $tenant->id);
            $request->merge([
                'tenant' => $tenant,
                'tenant_id' => $tenant->id,
            ]);
        }

        if ($this->requiresCredits($request) && ! $this->shouldBypassCreditCheck($request, $tenant)) {
            $includedSlug = $request->input('service_package_slug');

            $violation = $this->limitEvaluator->assessEventCreation(
                $tenant,
                is_string($includedSlug) && $includedSlug !== '' ? $includedSlug : null
            );

            if ($violation !== null) {
                return ApiError::response(
                    $violation['code'],
                    $violation['title'],
                    $violation['message'],
                    $violation['status'],
                    $violation['meta']
                );
            }
        }

        return $next($request);
    }

    private function shouldBypassCreditCheck(Request $request, Tenant $tenant): bool
    {
        $user = $request->user();
        if (! $user instanceof User) {
            return false;
        }

        if (! $user->isSuperAdmin()) {
            return false;
        }

        if (! $user->tenant_id) {
            return false;
        }

        return (int) $user->tenant_id === (int) $tenant->id;
    }

    private function requiresCredits(Request $request): bool
    {
        return $request->isMethod('post')
            && $request->routeIs('api.v1.tenant.events.store');
    }

    private function resolveTenant(Request $request): Tenant
    {
        $user = $request->user();
        if ($user && isset($user->tenant) && $user->tenant instanceof Tenant) {
            return $user->tenant;
        }

        $tenantId = $request->attributes->get('tenant_id');
        if (! $tenantId && $user && isset($user->tenant_id)) {
            $tenantId = $user->tenant_id;
        }

        if (! $tenantId) {
            abort(401, 'Unauthenticated');
        }

        return Tenant::findOrFail($tenantId);
    }
}
