<?php

declare(strict_types=1);

namespace ImovelZapAi\SuperAdmin\Application\Actions;

use ImovelZapAi\SuperAdmin\Application\Services\PlatformAuditLogger;
use ImovelZapAi\Tenancy\Application\Actions\CreateTenantAction;
use ImovelZapAi\Tenancy\Domain\Enums\TenantStatus;
use ImovelZapAi\Tenancy\Infrastructure\Persistence\Eloquent\TenantModel;

final class PlatformCreateTenantAction
{
    public function __construct(
        private readonly CreateTenantAction $createTenant,
        private readonly PlatformAuditLogger $audit,
    ) {}

    public function execute(string $name, string $slug, TenantStatus $status = TenantStatus::Trial): TenantModel
    {
        $tenant = $this->createTenant->execute($name, $slug);
        if ($status !== TenantStatus::Active) {
            $tenant->forceFill(['status' => $status])->save();
        }

        $this->audit->log(
            'tenant.created',
            TenantModel::class,
            (string) $tenant->id,
            (string) $tenant->id,
            ['name' => $name, 'slug' => $slug, 'status' => $status->value],
        );

        return $tenant->fresh();
    }
}
