package taskcenter

import (
	"context"
	"testing"

	"bindbox-game/internal/repository/mysql"
)

// TestInviteLogicSymmetry 专项测试：验证邀请人数在不同配置下的统计对称性
func TestInviteLogicSymmetry(t *testing.T) {
	repo, err := mysql.NewSQLiteRepoForTest()
	if err != nil {
		t.Fatalf("创建 repo 失败: %v", err)
	}
	db := repo.GetDbW()
	initTestTables(t, db)

	// 手动补齐必要的表结构（集成测试需要）
	db.Exec(`CREATE TABLE orders (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		user_id INTEGER NOT NULL,
		status INTEGER NOT NULL DEFAULT 1,
		source_type INTEGER NOT NULL DEFAULT 0,
		total_amount INTEGER NOT NULL DEFAULT 0,
		remark TEXT,
		deleted_at DATETIME
	);`)
	db.Exec(`CREATE TABLE user_invites (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		inviter_id INTEGER NOT NULL,
		invitee_id INTEGER NOT NULL,
		created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
		deleted_at DATETIME
	);`)
	db.Exec(`CREATE TABLE activity_draw_logs (order_id INTEGER, issue_id INTEGER);`)
	db.Exec(`CREATE TABLE activity_issues (id INTEGER, activity_id INTEGER);`)

	svc := New(nil, repo, nil, nil, nil)
	inviterID := int64(888)

	// === 数据准备 ===
	// 邀请了 3 个人：101, 102, 103
	db.Exec("INSERT INTO user_invites (inviter_id, invitee_id) VALUES (?, 101), (?, 102), (?, 103)", inviterID, inviterID, inviterID)

	// 只有 101 在活动 77 中下过单并开奖
	db.Exec("INSERT INTO activity_issues (id, activity_id) VALUES (1, 77)")
	db.Exec("INSERT INTO orders (id, user_id, status, total_amount, source_type) VALUES (10, 101, 2, 100, 0)")
	db.Exec("INSERT INTO activity_draw_logs (order_id, issue_id) VALUES (10, 1)")

	// === 场景 1：全局任务 (ActivityID = 0) ===
	t.Run("GlobalInviteTask", func(t *testing.T) {
		taskID, _ := InsertTaskWithTierAndReward(t, db, TaskCombination{Metric: MetricInviteCount})
		db.Exec("UPDATE task_center_task_tiers SET activity_id = 0 WHERE task_id = ?", taskID)

		progress, _ := svc.GetUserProgress(context.Background(), inviterID, taskID)
		if progress.InviteCount != 3 {
			t.Errorf("全局任务失败: 期望 3 (注册即计入), 实际 %d", progress.InviteCount)
		} else {
			t.Logf("✅ 全局任务验证通过: 邀请人数为 %d (与邀请记录页一致)", progress.InviteCount)
		}
	})

	// === 场景 2：特定活动任务 (ActivityID = 77) ===
	t.Run("ActivitySpecificInviteTask", func(t *testing.T) {
		taskID, _ := InsertTaskWithTierAndReward(t, db, TaskCombination{Metric: MetricInviteCount})
		db.Exec("UPDATE task_center_task_tiers SET activity_id = 77 WHERE task_id = ?", taskID)

		progress, _ := svc.GetUserProgress(context.Background(), inviterID, taskID)
		if progress.InviteCount != 1 {
			t.Errorf("活动专属任务失败: 期望 1 (仅统计活动77的有效转化), 实际 %d", progress.InviteCount)
		} else {
			t.Logf("✅ 活动专属任务验证通过: 邀请人数为 %d (仅包含活动77下的有效用户)", progress.InviteCount)
		}
	})
}
