<?php

namespace App\Domains\Bootstrap\Services;

use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Services\TenantInformationService;
use App\Domains\Tenant\Support\TenantDomainNormalizer;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class TenantBootstrapService
{
    public function __construct(protected TenantInformationService $tenantInformationService) {}

    public function get(string $domain, string $path = '/'): Tenant
    {
        $candidateBasePaths = TenantDomainNormalizer::basePathCandidates($path);
        $tenantsByBasePath = Tenant::query()
            ->where('dominio', $domain)
            ->whereIn('base_path', $candidateBasePaths)
            ->get()
            ->keyBy('base_path');

        $tenant = collect($candidateBasePaths)
            ->map(fn (string $candidate): ?Tenant => $tenantsByBasePath->get($candidate))
            ->first(fn (?Tenant $candidate): bool => $candidate !== null);

        if (! $tenant instanceof Tenant) {
            throw (new ModelNotFoundException)->setModel(Tenant::class);
        }

        return $this->tenantInformationService->load(
            $tenant,
            [
                'menues' => fn ($query) => $query->whereHas(
                    'roles',
                    fn ($query) => $query->where('codigo', RoleCode::User->value)
                ),
                'categories' => fn ($query) => $query->orderBy('nombre'),
            ]
        );
    }
}
