<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\BaseModel;

final class AutomationWorkflowModel extends BaseModel
{
    protected string $table = 'automation_workflows';
    protected array $fillable = ['name', 'trigger_type', 'trigger_config', 'is_active'];
    protected bool $softDeletes = true;
    protected bool $auditStamps = true;

    public function activeByTrigger(string $triggerType): array
    {
        $stmt = $this->db->prepare(
            'SELECT * FROM automation_workflows WHERE trigger_type = :trigger AND is_active = 1 AND deleted_at IS NULL'
        );
        $stmt->execute(['trigger' => $triggerType]);

        return $stmt->fetchAll();
    }

    public function steps(int $workflowId): array
    {
        $stmt = $this->db->prepare('SELECT * FROM automation_steps WHERE workflow_id = :id ORDER BY sort_order');
        $stmt->execute(['id' => $workflowId]);

        return $stmt->fetchAll();
    }

    public function addStep(int $workflowId, string $stepType, array $config, int $sortOrder, ?string $parentBranch = null): int
    {
        $stmt = $this->db->prepare(
            'INSERT INTO automation_steps (workflow_id, step_type, config, sort_order, parent_branch)
             VALUES (:workflow_id, :step_type, :config, :sort_order, :branch)'
        );
        $stmt->execute([
            'workflow_id' => $workflowId,
            'step_type' => $stepType,
            'config' => json_encode($config),
            'sort_order' => $sortOrder,
            'branch' => $parentBranch,
        ]);

        return (int) $this->db->lastInsertId();
    }

    public function allWithStepCounts(): array
    {
        return $this->db->query(
            'SELECT w.*, COUNT(s.id) AS step_count
             FROM automation_workflows w
             LEFT JOIN automation_steps s ON s.workflow_id = w.id
             WHERE w.deleted_at IS NULL
             GROUP BY w.id
             ORDER BY w.name'
        )->fetchAll();
    }

    public function runsFor(int $workflowId): array
    {
        $stmt = $this->db->prepare(
            'SELECT * FROM automation_runs WHERE workflow_id = :id ORDER BY started_at DESC LIMIT 50'
        );
        $stmt->execute(['id' => $workflowId]);

        return $stmt->fetchAll();
    }
}
