<?php

declare(strict_types=1);

namespace ImovelZapAi\Analytics\Application\Queries;

use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use ImovelZapAi\Analytics\Domain\Enums\AlertStatus;
use ImovelZapAi\Analytics\Infrastructure\Persistence\Eloquent\AnalyticsAlertModel;

final class ListAnalyticsAlertsQuery
{
    /**
     * @param  array{status?: string, limit?: int, per_page?: int}  $filters
     */
    public function execute(string $tenantId, array $filters = []): LengthAwarePaginator|array
    {
        $query = AnalyticsAlertModel::query()
            ->where('tenant_id', $tenantId)
            ->orderByDesc('triggered_at');

        if (isset($filters['status'])) {
            $status = AlertStatus::tryFrom((string) $filters['status']);
            if ($status !== null) {
                $query->where('status', $status->value);
            }
        }

        if (isset($filters['limit'])) {
            return $query->limit((int) $filters['limit'])->get()->all();
        }

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