package store

import (
	"context"
	"strings"
	"time"

	"github.com/easyai/easyai-ai-gateway/apps/api/internal/auth"
)

type DailyTokenUsage struct {
	Date              string  `json:"date"`
	TotalTokens       int64   `json:"totalTokens"`
	InputTokens       int64   `json:"inputTokens"`
	OutputTokens      int64   `json:"outputTokens"`
	CachedInputTokens int64   `json:"cachedInputTokens"`
	ResourcePoints    float64 `json:"resourcePoints"`
	TaskCount         int64   `json:"taskCount"`
}

func (s *Store) ListDailyTokenUsage(ctx context.Context, user *auth.User, from, to time.Time, timezone string) ([]DailyTokenUsage, error) {
	gatewayUserID := localGatewayUserID(user)
	apiKeyID := ""
	userID := ""
	if user != nil {
		apiKeyID = strings.TrimSpace(user.APIKeyID)
		userID = strings.TrimSpace(user.ID)
	}
	if gatewayUserID == "" && userID == "" {
		return nil, ErrLocalUserRequired
	}
	rows, err := s.pool.Query(ctx, `
SELECT to_char(created_at AT TIME ZONE $6, 'YYYY-MM-DD') AS usage_day,
       COALESCE(sum(
         CASE WHEN jsonb_typeof(usage->'totalTokens') = 'number' THEN (usage->>'totalTokens')::numeric
              WHEN jsonb_typeof(usage->'total_tokens') = 'number' THEN (usage->>'total_tokens')::numeric
              ELSE COALESCE(CASE WHEN jsonb_typeof(usage->'inputTokens') = 'number' THEN (usage->>'inputTokens')::numeric ELSE 0 END, 0)
                 + COALESCE(CASE WHEN jsonb_typeof(usage->'outputTokens') = 'number' THEN (usage->>'outputTokens')::numeric ELSE 0 END, 0)
         END
       ), 0)::bigint AS total_tokens,
       COALESCE(sum(CASE WHEN jsonb_typeof(usage->'inputTokens') = 'number' THEN (usage->>'inputTokens')::numeric WHEN jsonb_typeof(usage->'input_tokens') = 'number' THEN (usage->>'input_tokens')::numeric ELSE 0 END), 0)::bigint,
       COALESCE(sum(CASE WHEN jsonb_typeof(usage->'outputTokens') = 'number' THEN (usage->>'outputTokens')::numeric WHEN jsonb_typeof(usage->'output_tokens') = 'number' THEN (usage->>'output_tokens')::numeric ELSE 0 END), 0)::bigint,
       COALESCE(sum(CASE WHEN jsonb_typeof(usage->'cachedInputTokens') = 'number' THEN (usage->>'cachedInputTokens')::numeric WHEN jsonb_typeof(usage->'cached_input_tokens') = 'number' THEN (usage->>'cached_input_tokens')::numeric ELSE 0 END), 0)::bigint,
       COALESCE(sum(final_charge_amount), 0)::float8,
       count(*)::bigint
FROM gateway_tasks
WHERE status = 'succeeded'
  AND ((NULLIF($1, '')::uuid IS NOT NULL AND gateway_user_id = NULLIF($1, '')::uuid)
    OR (NULLIF($1, '')::uuid IS NULL AND NULLIF($2, '') IS NOT NULL AND user_id = $2))
  AND (NULLIF($3, '') IS NULL OR api_key_id = $3)
  AND created_at >= ($4::date::timestamp AT TIME ZONE $6)
  AND created_at < (($5::date + 1)::timestamp AT TIME ZONE $6)
GROUP BY usage_day
ORDER BY usage_day`, gatewayUserID, userID, apiKeyID, from.Format("2006-01-02"), to.Format("2006-01-02"), timezone)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := make([]DailyTokenUsage, 0)
	for rows.Next() {
		var item DailyTokenUsage
		if err := rows.Scan(&item.Date, &item.TotalTokens, &item.InputTokens, &item.OutputTokens, &item.CachedInputTokens, &item.ResourcePoints, &item.TaskCount); err != nil {
			return nil, err
		}
		items = append(items, item)
	}
	return items, rows.Err()
}
