<?php

namespace App\Domains\Tenant\Controllers;

use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Requests\BootstrapTenantRequest;
use App\Domains\Tenant\Resources\TenantResource;
use App\Domains\Tenant\Services\TenantInformationService;
use App\Http\Controllers\Controller;

class BootstrapTenantController extends Controller
{
    public function __construct(
        protected TenantInformationService $tenantInformationService
    ) {}

    public function __invoke(BootstrapTenantRequest $request): TenantResource
    {
        /** @var string $dominio */
        $dominio = $request->validated('dominio');

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