<?php

declare(strict_types=1);

namespace ImovelZapAi\Automation\Infrastructure\Persistence\Eloquent;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use ImovelZapAi\Automation\Domain\Enums\ExecutionStatus;
use ImovelZapAi\Shared\Infrastructure\Persistence\Concerns\BelongsToTenant;
use ImovelZapAi\Shared\Infrastructure\Persistence\Concerns\HasUuidPrimaryKey;

class AutomationExecutionModel extends Model
{
    use BelongsToTenant;
    use HasUuidPrimaryKey;

    protected $table = 'automation_executions';

    protected $fillable = [
        'tenant_id',
        'workflow_id',
        'trigger_event_key',
        'status',
        'context',
        'started_at',
        'finished_at',
        'error_message',
        'duration_ms',
    ];

    protected function casts(): array
    {
        return [
            'status' => ExecutionStatus::class,
            'context' => 'array',
            'started_at' => 'datetime',
            'finished_at' => 'datetime',
            'duration_ms' => 'integer',
        ];
    }

    public function workflow(): BelongsTo
    {
        return $this->belongsTo(AutomationWorkflowModel::class, 'workflow_id');
    }

    public function logs(): HasMany
    {
        return $this->hasMany(AutomationLogModel::class, 'execution_id')->orderBy('created_at');
    }
}
