<?php

declare(strict_types=1);

namespace ImovelZapAi\Automation\Application\Queries;

use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use ImovelZapAi\Automation\Infrastructure\Persistence\Eloquent\AutomationExecutionModel;

final class ListExecutionsQuery
{
    /**
     * @param  array{workflow_id?: string, status?: string, per_page?: int}  $filters
     */
    public function execute(string $tenantId, array $filters = []): LengthAwarePaginator
    {
        $query = AutomationExecutionModel::query()
            ->where('tenant_id', $tenantId)
            ->with(['workflow'])
            ->orderByDesc('created_at');

        if (! empty($filters['workflow_id'])) {
            $query->where('workflow_id', $filters['workflow_id']);
        }

        if (! empty($filters['status'])) {
            $query->where('status', $filters['status']);
        }

        return $query->paginate((int) ($filters['per_page'] ?? 20));
    }
}
