/**
 * Live Matches Cleanup Script
 *
 * Bitmiş maçları live_matches tablosundan siler.
 * Kullanım: npx ts-node -r tsconfig-paths/register src/scripts/cleanup-live-matches.ts
 */

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

const FINISHED_STATUSES = ["Finished", "Played", "FT", "AET", "PEN", "Ended"];
const FINISHED_STATES = ["Finished", "post", "FT", "postGame"];
const LIVE_STATUSES = [
  "LIVE",
  "1H",
  "2H",
  "HT",
  "1Q",
  "2Q",
  "3Q",
  "4Q",
  "Playing",
  "Half Time",
];
const LIVE_STATES = ["live", "firsthalf", "secondhalf"];

async function cleanupLiveMatches() {
  const prisma = new PrismaClient();

  try {
    console.log("🧹 Live matches temizliği başlıyor...");

    const now = Date.now();
    const finishedGraceMs = 6 * 60 * 60 * 1000;
    const staleGraceMs = 24 * 60 * 60 * 1000;
    const finishedBefore = BigInt(now - finishedGraceMs);
    const staleBefore = BigInt(now - staleGraceMs);

    const totalBefore = await prisma.liveMatch.count();
    const outdatedCount = await prisma.liveMatch.count({
      where: {
        mstUtc: { lt: BigInt(now) },
      },
    });
    const finishedPastCount = await prisma.liveMatch.count({
      where: {
        mstUtc: { lt: finishedBefore },
        OR: [
          { status: { in: FINISHED_STATUSES } },
          { state: { in: FINISHED_STATES } },
        ],
      },
    });

    console.log("📊 Mevcut durum:");
    console.log(`   Toplam live_matches: ${totalBefore}`);
    console.log(`   Geçmiş zamanlı kayıt: ${outdatedCount}`);
    console.log(
      `   Bitmiş ve grace süresini aşmış kayıt: ${finishedPastCount}`,
    );

    const deleted = await prisma.liveMatch.deleteMany({
      where: {
        OR: [
          {
            mstUtc: { lt: finishedBefore },
            OR: [
              { status: { in: FINISHED_STATUSES } },
              { state: { in: FINISHED_STATES } },
            ],
          },
          {
            mstUtc: { lt: staleBefore },
            NOT: {
              OR: [
                { status: { in: LIVE_STATUSES } },
                { state: { in: LIVE_STATES } },
              ],
            },
          },
        ],
      },
    });

    const totalAfter = await prisma.liveMatch.count();

    console.log("\n✅ Temizlik tamamlandı!");
    console.log(`   Silinen maç: ${deleted.count}`);
    console.log(`   Kalan maç: ${totalAfter}`);

    const states = await prisma.$queryRaw`
      SELECT state, COUNT(*)::int as count 
      FROM live_matches 
      GROUP BY state
    `;

    console.log("\n📋 Kalan maçların durumları:");
    (states as any).forEach((s: any) => {
      console.log(`   ${s.state || "null"}: ${s.count}`);
    });
  } catch (error) {
    console.error("❌ Hata:", error);
  } finally {
    await prisma.$disconnect();
  }
}

void cleanupLiveMatches();
