import { CardTier, PrismaClient } from "@prisma/client";

const db = new PrismaClient();

function buildCardTierMap(totalPlayers: number) {
  const goldCutoff = Math.max(1, Math.ceil(totalPlayers * 0.2));
  const silverCutoff = Math.max(goldCutoff, Math.ceil(totalPlayers * 0.5));

  return (index: number): CardTier => {
    if (index < goldCutoff) return "GOLD";
    if (index < silverCutoff) return "SILVER";
    return "BRONZE";
  };
}

async function main() {
  console.log("Seeding sample quiz data...");

  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const windowStart = new Date();
  windowStart.setHours(18, 0, 0, 0);

  const windowEnd = new Date();
  windowEnd.setHours(21, 0, 0, 0);

  const existingQuiz = await db.dailyQuiz.findUnique({ where: { date: today } });
  if (!existingQuiz) {
    const quiz = await db.dailyQuiz.create({
      data: {
        date: today,
        windowStart,
        windowEnd,
        winnersCount: 3,
        goldMinCorrect: 4,
        silverMinCorrect: 3,
        bronzeMinCorrect: 2,
        questions: {
          create: [
            {
              questionText: "کدام بازیکن بیشترین گل را در جام جهانی 2022 زده است؟",
              options: ["کیلیان امباپه", "لیونل مسی", "کریستیانو رونالدو", "نیمار"],
              correctAnswer: 0,
              order: 0,
            },
            {
              questionText: "قهرمان جام جهانی 2022 کدام تیم بود؟",
              options: ["فرانسه", "آرژانتین", "برزیل", "آلمان"],
              correctAnswer: 1,
              order: 1,
            },
            {
              questionText: "جام جهانی 2026 در کدام کشورها برگزار می شود؟",
              options: ["قطر", "آمریکا، کانادا، مکزیک", "روسیه", "برزیل"],
              correctAnswer: 1,
              order: 2,
            },
            {
              questionText: "اولین جام جهانی در چه سالی برگزار شد؟",
              options: ["1930", "1934", "1950", "1954"],
              correctAnswer: 0,
              order: 3,
            },
          ],
        },
      },
      include: { questions: true },
    });

    console.log(`Created quiz with ${quiz.questions.length} questions`);
  } else {
    console.log("Quiz for today already exists, skipping quiz creation");
  }

  const players = await db.player.findMany({
    orderBy: [{ totalPoints: "desc" }, { name: "asc" }],
  });

  if (players.length > 0) {
    const resolveTier = buildCardTierMap(players.length);

    await db.$transaction(
      players.map((player, index) =>
        db.player.update({
          where: { id: player.id },
          data: {
            cardTier: resolveTier(index),
            isGoldenCardEligible: resolveTier(index) === "GOLD",
          },
        })
      )
    );

    console.log(`Assigned card tiers to ${players.length} players based on total points`);
  } else {
    console.log("No players found for card tier assignment");
  }

  console.log("Sample quiz data seeded successfully");
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await db.$disconnect();
  });
