<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Config;
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;

class InitializeTenancyByDomain extends \Stancl\Tenancy\Middleware\InitializeTenancyByDomain
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    #[\Override]
    public function handle($request, Closure $next)
    {
        self::$onFail = fn($e) => response($request->header('x-tenant') . ' Not Found', 404);

        return $this->initializeTenancy(
            $request,
            $next,
            str_replace('www.', '', $request->header('x-tenant') ?? '')
        );
    }

    #[\Override]
    public function initializeTenancy($request, $next, ...$resolverArguments)
    {
        try {
            $this->tenancy->initialize(
                $this->resolver->resolve(...$resolverArguments)
            );
        } catch (TenantCouldNotBeIdentifiedException $e) {
            $onFail = static::$onFail ?? function ($e) {
                throw $e;
            };

            return $onFail($e, $request, $next);
        }

        Config::set('sanctum.stateful', tenant()->domains->pluck('domain')->toArray());
        return $next($request);
    }
}
