<?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 PackageMiddleware
{
    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->requiresPackageCheck($request) && ! $this->shouldBypassPackageCheck($request, $tenant)) {
            $violation = $this->detectViolation($request, $tenant);

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

        return $next($request);
    }

    private function shouldBypassPackageCheck(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 requiresPackageCheck(Request $request): bool
    {
        return $request->isMethod('post') && (
            $request->routeIs('api.v1.tenant.events.store') ||
            $request->routeIs('api.v1.tenant.events.photos.store')
        );
    }

    private function detectViolation(Request $request, Tenant $tenant): ?array
    {
        if ($request->routeIs('api.v1.tenant.events.store')) {
            $includedSlug = $request->input('service_package_slug');

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

        if ($request->routeIs('api.v1.tenant.events.photos.store')) {
            $eventId = (int) $request->input('event_id');
            if (! $eventId) {
                return [
                    'code' => 'event_id_missing',
                    'title' => 'Event required',
                    'message' => 'An event must be specified to upload photos.',
                    'status' => 422,
                    'meta' => [
                        'scope' => 'photos',
                    ],
                ];
            }

            return $this->limitEvaluator->assessPhotoUpload($tenant, $eventId);
        }

        return null;
    }

    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);
    }
}
