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

const prisma = new PrismaClient();

async function main() {
  console.log("🔍 Checking for potential duplicate matches...");

  // Group by unique match characteristics
  // Since we can't easily do GROUP BY with HAVING count > 1 in Prisma standard API without raw query,
  // we'll use a raw query for efficiency.

  const duplicates = await prisma.$queryRaw<
    {
      home_team_id: string;
      away_team_id: string;
      mst_utc: bigint;
      count: bigint;
      ids: string[];
    }[]
  >`
    SELECT 
      home_team_id, 
      away_team_id, 
      mst_utc, 
      COUNT(*) as count,
      array_agg(id) as ids
    FROM matches
    WHERE home_team_id IS NOT NULL 
      AND away_team_id IS NOT NULL
    GROUP BY home_team_id, away_team_id, mst_utc
    HAVING COUNT(*) > 1
    ORDER BY count DESC
    LIMIT 50;
  `;

  if (duplicates.length === 0) {
    console.log(
      "✅ No duplicate matches found based on (HomeTeam + AwayTeam + Date).",
    );
    return;
  }

  console.log(`⚠️ Found ${duplicates.length} sets of duplicate matches:\n`);

  for (const group of duplicates) {
    const homeTeam = await prisma.team.findUnique({
      where: { id: group.home_team_id },
      select: { name: true },
    });
    const awayTeam = await prisma.team.findUnique({
      where: { id: group.away_team_id },
      select: { name: true },
    });

    const date = new Date(Number(group.mst_utc)).toISOString();
    console.log(
      `📅 ${date} | ${homeTeam?.name} vs ${awayTeam?.name} (Count: ${group.count})`,
    );
    console.log(`   IDs: ${group.ids.join(", ")}`);

    // Check details of the duplicates to see if one is complete and one is not
    for (const id of group.ids) {
      const match = await prisma.match.findUnique({
        where: { id },
        include: {
          oddCategories: { select: { dbId: true } },
          footballTeamStats: { select: { id: true } },
          basketballPlayerStats: { select: { id: true } },
          playerEvents: { select: { id: true } },
          officials: { select: { id: true } },
        },
      });

      if (match) {
        const counts = [
          match.oddCategories.length > 0 ? "Odds" : "",
          match.footballTeamStats.length > 0 ? "Stats" : "",
          match.playerEvents.length > 0 ? "Events" : "",
          match.officials.length > 0 ? "Officials" : "",
        ]
          .filter(Boolean)
          .join(", ");

        console.log(
          `   - [${id}] Status: ${match.status} | Score: ${match.scoreHome}-${match.scoreAway} | Data: ${counts || "None"}`,
        );
      }
    }
    console.log("---------------------------------------------------");
  }
}

main()
  .catch((e) => console.error(e))
  .finally(async () => {
    await prisma.$disconnect();
  });
