-- name: InsertUsage :exec
INSERT INTO llm_usage (
    conversation_id, message_id, user_id, endpoint_id, model_id,
    prompt_tokens, completion_tokens, thinking_tokens, cost_usd
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9);

-- name: SummarizeUsageByUser :many
SELECT user_id,
       SUM(prompt_tokens)::int     AS prompt_tokens,
       SUM(completion_tokens)::int AS completion_tokens,
       SUM(thinking_tokens)::int   AS thinking_tokens,
       SUM(cost_usd)::numeric      AS cost_usd
FROM llm_usage
WHERE created_at >= $1 AND created_at < $2
GROUP BY user_id
ORDER BY cost_usd DESC;

-- name: SummarizeUsageByModel :many
SELECT model_id,
       SUM(prompt_tokens)::int     AS prompt_tokens,
       SUM(completion_tokens)::int AS completion_tokens,
       SUM(thinking_tokens)::int   AS thinking_tokens,
       SUM(cost_usd)::numeric      AS cost_usd
FROM llm_usage
WHERE created_at >= $1 AND created_at < $2
GROUP BY model_id
ORDER BY cost_usd DESC;

-- name: SummarizeUsageByDay :many
SELECT date_trunc('day', created_at)::timestamptz AS day,
       SUM(prompt_tokens)::int     AS prompt_tokens,
       SUM(completion_tokens)::int AS completion_tokens,
       SUM(thinking_tokens)::int   AS thinking_tokens,
       SUM(cost_usd)::numeric      AS cost_usd
FROM llm_usage
WHERE created_at >= $1 AND created_at < $2
GROUP BY day
ORDER BY day;

-- name: SummarizeUserDaily :many
SELECT date_trunc('day', created_at)::timestamptz AS day,
       SUM(prompt_tokens)::int     AS prompt_tokens,
       SUM(completion_tokens)::int AS completion_tokens,
       SUM(thinking_tokens)::int   AS thinking_tokens,
       SUM(cost_usd)::numeric      AS cost_usd
FROM llm_usage
WHERE user_id = $1 AND created_at >= $2 AND created_at < $3
GROUP BY day
ORDER BY day;
