package httpapi

import (
	"testing"
	"time"

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

func TestAdvancedMediaScopeAliases(t *testing.T) {
	tests := []struct {
		kind  string
		scope string
	}{
		{kind: "images.vectorize", scope: "image_vectorize"},
		{kind: "images.vectorize", scope: "image"},
		{kind: "images.vectorize", scope: "vectorize"},
		{kind: "videos.upscales", scope: "video_enhance"},
		{kind: "videos.upscales", scope: "video"},
		{kind: "videos.upscales", scope: "video_upscale"},
	}
	for _, test := range tests {
		user := &auth.User{APIKeyID: "key", APIKeyScopes: []string{test.scope}}
		if !apiKeyScopeAllowed(user, test.kind) {
			t.Fatalf("scope %q should allow %q", test.scope, test.kind)
		}
	}
	if apiKeyScopeAllowed(&auth.User{APIKeyID: "key", APIKeyScopes: []string{"chat"}}, "videos.upscales") {
		t.Fatal("chat scope must not allow video upscale")
	}
}

func TestFillDailyTokenUsageDaysKeepsGapsAndStreaks(t *testing.T) {
	location, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		t.Fatal(err)
	}
	from := time.Date(2026, 7, 20, 0, 0, 0, 0, location)
	to := time.Date(2026, 7, 24, 0, 0, 0, 0, location)
	items, summary := fillDailyTokenUsageDays(map[string]store.DailyTokenUsage{
		"2026-07-20": {Date: "2026-07-20", TotalTokens: 10, TaskCount: 1},
		"2026-07-22": {Date: "2026-07-22", TotalTokens: 20, TaskCount: 1},
		"2026-07-23": {Date: "2026-07-23", TotalTokens: 30, TaskCount: 2},
		"2026-07-24": {Date: "2026-07-24", TotalTokens: 40, TaskCount: 1},
	}, from, to)
	if len(items) != 5 || items[1].Date != "2026-07-21" || items[1].TaskCount != 0 {
		t.Fatalf("daily usage should contain continuous zero days: %+v", items)
	}
	if summary.CumulativeTokens != 100 || summary.PeakDailyTokens != 40 || summary.CurrentStreakDays != 3 || summary.LongestStreakDays != 3 {
		t.Fatalf("unexpected daily usage summary: %+v", summary)
	}
}

func TestAdvancedMediaDefaultModels(t *testing.T) {
	if got := canonicalTaskModelName("images.vectorize", ""); got != "easy-image-vectorizer-1" {
		t.Fatalf("vectorizer default model=%q", got)
	}
	if got := canonicalTaskModelName("videos.upscales", ""); got != "easy-proteus-standard-4" {
		t.Fatalf("Topaz default model=%q", got)
	}
}
