<?php

namespace App\Modules\HR\Recruitment\Middleware;

use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\Admin\Tenancy\Services\TenantContext;
use App\Modules\HR\Recruitment\Services\CareerPortalSettingsService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ResolveCareerPortalTenant
{
    public function __construct(
        private readonly TenantContext $tenantContext,
        private readonly CareerPortalSettingsService $settings,
    ) {}

    public function handle(Request $request, Closure $next): Response
    {
        $slug = (string) $request->route('tenant');
        $tenant = Tenant::query()
            ->where('slug', $slug)
            ->where('is_active', true)
            ->first();

        if ($tenant === null) {
            abort(404, __('recruitment.career_portal.errors.tenant_not_found'));
        }

        $this->tenantContext->setTenantId((int) $tenant->id);
        $settings = $this->settings->getOrDefaults((int) $tenant->id);

        if (! $settings->is_enabled) {
            return response()->view('pages.careers.disabled', [
                'tenant' => $tenant,
                'settings' => $settings,
            ], 503);
        }

        $request->attributes->set('career_tenant', $tenant);
        $request->attributes->set('career_settings', $settings);

        return $next($request);
    }
}
