<?php

namespace App\Http\Middleware\Store;

use App\Services\Contract\ContractAcceptanceService;
use Closure;
use Illuminate\Http\Request;

class RequiresContractAcceptance
{
    public function __construct(private readonly ContractAcceptanceService $service) {}

    /**
     * Bypass route adları (interstitial sayfa kendisi, kabul endpoint'i, logout vs.).
     */
    private const SKIP_ROUTE_NAMES = [
        'store.auth.contracts.pending',
        'store.auth.contracts.pending.accept', // POST endpoint that records the acceptance
        'store.auth.contracts.pending.skip',   // POST endpoint that records the skip (grace period)
        'store.auth.contracts.accept',         // legacy /clientarea/contracts/{slug}/accept route
        'store.auth.contracts.detail',
        'store.auth.logout',
        'legal.contract.show', // public legal page (Task 18 fix added this)
    ];

    public function handle(Request $request, Closure $next): \Symfony\Component\HttpFoundation\Response
    {
        $client = $request->user('client');
        if (! $client) {
            return $next($request);
        }

        // Bypass the gate while the user is in switched mode. The active context is
        // the owner's account; the owner's pending is the owner's responsibility
        // (they get the gate on their own login). The switched actor's own pending
        // only applies when they're acting as themselves.
        if (session('active_client_id') && (int) session('active_client_id') !== (int) $client->id) {
            return $next($request);
        }

        $routeName = $request->route()?->getName();
        if ($routeName && in_array($routeName, self::SKIP_ROUTE_NAMES, true)) {
            return $next($request);
        }

        if ($this->service->hasPending($client)) {
            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'error' => 'contract_acceptance_required',
                    'redirect' => route('store.auth.contracts.pending'),
                ], 423); // 423 Locked
            }

            return redirect()->route('store.auth.contracts.pending');
        }

        return $next($request);
    }
}
