<?php

namespace App\Modules\Admin\Tenancy\Middleware;

use App\Models\User;
use App\Modules\Admin\Tenancy\Services\SubscriptionAccessService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureTenantSubscriptionWritable
{
    public function __construct(
        private readonly SubscriptionAccessService $subscriptionAccess,
    ) {}

    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        if ($user === null || $user->isAdmin()) {
            return $next($request);
        }

        if ($this->allowsMutatingMethod($request, $user) === false) {
            return $next($request);
        }

        $tenant = $user->tenant;
        if ($tenant === null) {
            return $next($request);
        }

        if (! $this->subscriptionAccess->tenantSubscriptionIsReadOnly($tenant)) {
            return $next($request);
        }

        if ($request->expectsJson()) {
            return response()->json([
                'message' => __('subscription.read_only.message'),
            ], 403);
        }

        return response()->view('pages.subscription.read-only', [
            'upgradeUrl' => route('dashboard.index').'#dashboard-modules',
        ], 403);
    }

    private function allowsMutatingMethod(Request $request, User $user): bool
    {
        $method = strtoupper($request->method());
        if (in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
            return false;
        }

        if ($method === 'POST' && $request->routeIs('logout')) {
            return false;
        }

        if ($method === 'POST' && $request->routeIs([
            'notifications.read',
            'notifications.read-all',
            'me.notifications.read',
            'me.notifications.read-all',
        ])) {
            return false;
        }

        return true;
    }
}
