<?php

declare(strict_types=1);

namespace ImovelZapAi\Automation\Application\Actions;

use App\Models\User;
use ImovelZapAi\Automation\Domain\Enums\WorkflowStatus;
use ImovelZapAi\Automation\Domain\Exceptions\AutomationException;
use ImovelZapAi\Automation\Infrastructure\Persistence\Eloquent\AutomationTemplateModel;
use ImovelZapAi\Automation\Infrastructure\Persistence\Eloquent\AutomationWorkflowModel;

final class InstallWorkflowTemplateAction
{
    public function __construct(
        private readonly CreateWorkflowAction $createWorkflow,
        private readonly ActivateWorkflowAction $activateWorkflow,
    ) {}

    public function execute(string $tenantId, User $user, string $slug, bool $activate = false): AutomationWorkflowModel
    {
        $template = AutomationTemplateModel::query()
            ->where('slug', $slug)
            ->where('is_active', true)
            ->first();

        if ($template === null) {
            throw AutomationException::templateNotFound();
        }

        /** @var array<string, mixed>|null $definition */
        $definition = is_array($template->definition) ? $template->definition : null;

        if ($definition === null || empty($definition['trigger']['event_key'])) {
            throw AutomationException::invalidState('modelo sem gatilho configurado.');
        }

        $workflow = $this->createWorkflow->execute($tenantId, $user, [
            'name' => (string) ($definition['name'] ?? $template->name),
            'description' => $definition['description'] ?? $template->description,
            'status' => WorkflowStatus::Draft->value,
            'trigger' => $definition['trigger'],
            'conditions' => $definition['conditions'] ?? [],
            'actions' => $definition['actions'] ?? [],
        ]);

        $workflow->forceFill(['is_template_clone' => true])->save();

        if ($activate || (bool) ($definition['activate'] ?? false)) {
            return $this->activateWorkflow->execute($tenantId, (string) $workflow->id);
        }

        return $workflow->fresh(['triggers', 'conditions', 'actions']);
    }
}
