<?php

declare(strict_types=1);

namespace ImovelZapAi\AiGateway\Application\Queries;

use Carbon\CarbonImmutable;
use ImovelZapAi\AiGateway\Application\Data\AiGatewayUsageData;
use ImovelZapAi\AiGateway\Domain\Enums\AiRequestStatus;
use ImovelZapAi\AiGateway\Infrastructure\Persistence\Eloquent\AiRequestLogModel;

final class GetAiGatewayUsageQuery
{
    public function forTenant(string $tenantId, int $days = 30): AiGatewayUsageData
    {
        $since = CarbonImmutable::now()->subDays($days);

        $base = AiRequestLogModel::query()
            ->withoutGlobalScopes()
            ->where('tenant_id', $tenantId)
            ->where('created_at', '>=', $since);

        $totalRequests = (clone $base)->count();

        $successfulRequests = (clone $base)
            ->where('status', AiRequestStatus::Success->value)
            ->count();

        $failedRequests = (clone $base)
            ->where('status', AiRequestStatus::Failed->value)
            ->count();

        $quotaExceededRequests = (clone $base)
            ->where('status', AiRequestStatus::QuotaExceeded->value)
            ->count();

        $totalTokens = (int) (clone $base)->sum('total_tokens');
        $estimatedCostUsd = (float) (clone $base)->sum('estimated_cost_usd');

        $averageLatency = (clone $base)
            ->where('status', AiRequestStatus::Success->value)
            ->avg('latency_ms');

        /** @var array<string, int> $byTask */
        $byTask = (clone $base)
            ->selectRaw('task_type, COUNT(*) as total')
            ->groupBy('task_type')
            ->pluck('total', 'task_type')
            ->all();

        return new AiGatewayUsageData(
            totalRequests: $totalRequests,
            successfulRequests: $successfulRequests,
            failedRequests: $failedRequests,
            quotaExceededRequests: $quotaExceededRequests,
            totalTokens: $totalTokens,
            estimatedCostUsd: round($estimatedCostUsd, 6),
            averageLatencyMs: $averageLatency !== null ? round((float) $averageLatency, 1) : null,
            requestsByTaskType: $byTask,
        );
    }
}
