<?php

declare(strict_types=1);

namespace ImovelZapAi\Tenancy\Application\Actions;

use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use ImovelZapAi\Authentication\Application\Services\RoleProvisioner;
use ImovelZapAi\Conversations\Application\Actions\ConnectEvolutionInstanceAction;
use ImovelZapAi\Organizations\Application\Actions\EnsureOrganizationBootstrapAction;
use ImovelZapAi\Tenancy\Domain\Enums\OrganizationType;
use ImovelZapAi\Tenancy\Domain\Enums\TenantStatus;
use ImovelZapAi\Tenancy\Infrastructure\Persistence\Eloquent\TenantModel;
use Throwable;

final class CreateTenantAction
{
    public function __construct(
        private readonly RoleProvisioner $roleProvisioner,
        private readonly EnsureOrganizationBootstrapAction $bootstrapOrganization,
        private readonly ConnectEvolutionInstanceAction $connectEvolution,
    ) {}

    public function execute(
        string $name,
        string $slug,
        OrganizationType $type = OrganizationType::Agency,
    ): TenantModel {
        $slug = Str::slug($slug);

        if (TenantModel::query()->where('slug', $slug)->exists()) {
            throw ValidationException::withMessages([
                'slug' => ['Esta organização já existe.'],
            ]);
        }

        $tenant = TenantModel::query()->create([
            'name' => $name,
            'slug' => $slug,
            'status' => TenantStatus::Active,
            'type' => $type,
        ]);

        $this->roleProvisioner->provisionForTenant((string) $tenant->id);
        $this->bootstrapOrganization->execute((string) $tenant->id, $type);

        if ((bool) config('conversations.evolution.auto_provision_on_tenant_create', true)) {
            try {
                $this->connectEvolution->execute((string) $tenant->id);
            } catch (Throwable) {
                // Evolution opcional na criação; a tela WhatsApp completa o QR depois.
            }
        }

        return $tenant->fresh() ?? $tenant;
    }
}
