const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function inspectDatabase() {
  console.log('\n========================================');
  console.log('📊 VERİTABANI İNCELEME RAPORU');
  console.log('========================================\n');

  // 1. Countries
  console.log('🌍 ÜLKELER (Countries)');
  console.log('----------------------------------------');
  const countries = await prisma.country.findMany({ take: 20 });
  console.log(`Toplam: ${await prisma.country.count()} kayıt`);
  console.table(countries);

  // 2. Leagues
  console.log('\n🏆 LİGLER (Leagues)');
  console.log('----------------------------------------');
  const leagues = await prisma.league.findMany({
    take: 20,
    include: { country: true },
  });
  console.log(`Toplam: ${await prisma.league.count()} kayıt`);
  console.table(
    leagues.map((l) => ({
      id: l.id,
      name: l.name,
      sport: l.sport,
      country: l.country?.name || 'N/A',
      code: l.code,
    })),
  );

  // 3. Teams
  console.log('\n👥 TAKIMLAR (Teams)');
  console.log('----------------------------------------');
  const teams = await prisma.team.findMany({ take: 30 });
  console.log(`Toplam: ${await prisma.team.count()} kayıt`);
  console.table(teams);

  // 4. Players
  console.log('\n🏃 OYUNCULAR (Players)');
  console.log('----------------------------------------');
  const players = await prisma.player.findMany({ take: 20 });
  console.log(`Toplam: ${await prisma.player.count()} kayıt`);
  console.table(players);

  // 5. Matches
  console.log('\n⚽ MAÇLAR (Matches)');
  console.log('----------------------------------------');
  const matchCount = await prisma.match.count();
  console.log(`Toplam: ${matchCount} kayıt`);

  const matches = await prisma.match.findMany({
    take: 15,
    orderBy: { mstUtc: 'desc' },
    include: {
      homeTeam: true,
      awayTeam: true,
      league: true,
    },
  });
  console.table(
    matches.map((m) => ({
      id: m.id,
      homeTeam: m.homeTeam?.name || 'N/A',
      awayTeam: m.awayTeam?.name || 'N/A',
      score: `${m.scoreHome}-${m.scoreAway}`,
      status: m.status,
      state: m.state,
      sport: m.sport,
      iddaaCode: m.iddaaCode,
      mstUtc: new Date(Number(m.mstUtc)).toISOString(),
    })),
  );

  // 6. Live Matches
  console.log('\n🔴 CANLI MAÇLAR (Live Matches)');
  console.log('----------------------------------------');
  const liveMatchCount = await prisma.liveMatch.count();
  console.log(`Toplam: ${liveMatchCount} kayıt`);

  const liveMatches = await prisma.liveMatch.findMany({
    take: 10,
    include: {
      homeTeam: true,
      awayTeam: true,
      league: true,
    },
  });
  console.table(
    liveMatches.map((m) => ({
      id: m.id,
      homeTeam: m.homeTeam?.name || 'N/A',
      awayTeam: m.awayTeam?.name || 'N/A',
      score: `${m.scoreHome}-${m.scoreAway}`,
      state: m.state,
      status: m.status,
    })),
  );

  // 7. Match AI Features
  console.log('\n🤖 MAÇ AI ÖZELLİKLERİ (MatchAiFeatures)');
  console.log('----------------------------------------');
  const aiFeaturesCount = await prisma.matchAiFeature.count();
  console.log(`Toplam: ${aiFeaturesCount} kayıt`);

  const aiFeatures = await prisma.matchAiFeature.findMany({ take: 10 });
  console.table(aiFeatures);

  // 8. Odd Categories
  console.log('\n📊 ORAN KATEGORİLERİ (OddCategories)');
  console.log('----------------------------------------');
  const oddCategoriesCount = await prisma.oddCategory.count();
  console.log(`Toplam: ${oddCategoriesCount} kayıt`);

  const oddCategories = await prisma.oddCategory.findMany({
    take: 10,
    include: { match: true },
  });
  console.table(
    oddCategories.map((oc) => ({
      id: oc.dbId,
      matchId: oc.matchId,
      name: oc.name,
    })),
  );

  // 9. Odd Selections
  console.log('\n🎯 ORAN SEÇENEKLERİ (OddSelections)');
  console.log('----------------------------------------');
  const oddSelectionsCount = await prisma.oddSelection.count();
  console.log(`Toplam: ${oddSelectionsCount} kayıt`);

  const oddSelections = await prisma.oddSelection.findMany({ take: 15 });
  console.table(oddSelections);

  // 10. Predictions
  console.log('\n🔮 TAHMİNLER (Predictions)');
  console.log('----------------------------------------');
  const predictionsCount = await prisma.prediction.count();
  console.log(`Toplam: ${predictionsCount} kayıt`);

  const predictions = await prisma.prediction.findMany({
    take: 5,
    include: { match: true },
  });
  predictions.forEach((p, i) => {
    console.log(`\nPrediction ${i + 1}:`);
    console.log(`  Match: ${p.match?.matchName || p.matchId}`);
    console.log(
      `  JSON:`,
      JSON.stringify(p.predictionJson, null, 2).substring(0, 500) + '...',
    );
  });

  // 11. AI Predictions Log
  console.log('\n📝 AI TAHMİN LOGARI (AiPredictionsLog)');
  console.log('----------------------------------------');
  const aiLogCount = await prisma.aiPredictionsLog.count();
  console.log(`Toplam: ${aiLogCount} kayıt`);

  const aiLogs = await prisma.aiPredictionsLog.findMany({
    take: 10,
    orderBy: { createdAt: 'desc' },
  });
  console.table(
    aiLogs.map((log) => ({
      id: log.id,
      matchId: log.matchId,
      modelVersion: log.modelVersion,
      confidence: log.confidenceScore,
      isResolved: log.isResolved,
      isCorrect: log.isCorrect,
      createdAt: log.createdAt,
    })),
  );

  // 12. Users
  console.log('\n👤 KULLANICILAR (Users)');
  console.log('----------------------------------------');
  const usersCount = await prisma.user.count();
  console.log(`Toplam: ${usersCount} kayıt`);

  const users = await prisma.user.findMany({
    select: {
      id: true,
      email: true,
      firstName: true,
      lastName: true,
      role: true,
      subscriptionStatus: true,
      isActive: true,
      createdAt: true,
    },
  });
  console.table(users);

  // 13. User Coupons
  console.log('\n🎫 KULLANICI KUPONLARI (UserCoupons)');
  console.log('----------------------------------------');
  const couponsCount = await prisma.userCoupon.count();
  console.log(`Toplam: ${couponsCount} kayıt`);

  const coupons = await prisma.userCoupon.findMany({
    take: 10,
    include: { user: true },
  });
  console.table(
    coupons.map((c) => ({
      id: c.id,
      user: c.user.email,
      strategy: c.strategy,
      totalOdds: c.totalOdds,
      status: c.status,
      isPublic: c.isPublic,
    })),
  );

  // 14. Match Team Stats
  console.log('\n📈 MAÇ TAKIM İSTATİSTİKLERİ (MatchTeamStats)');
  console.log('----------------------------------------');
  const teamStatsCount = await prisma.matchTeamStats.count();
  console.log(`Toplam: ${teamStatsCount} kayıt`);

  const teamStats = await prisma.matchTeamStats.findMany({ take: 5 });
  console.table(teamStats);

  // 15. Match Player Stats
  console.log('\n🏀 MAÇ OYUNCU İSTATİSTİKLERİ (MatchPlayerStats)');
  console.log('----------------------------------------');
  const playerStatsCount = await prisma.matchPlayerStats.count();
  console.log(`Toplam: ${playerStatsCount} kayıt`);

  const playerStats = await prisma.matchPlayerStats.findMany({ take: 5 });
  console.table(playerStats);

  // 16. Match Player Events
  console.log('\n⚡ MAÇ OLAYLARI (MatchPlayerEvents)');
  console.log('----------------------------------------');
  const eventsCount = await prisma.matchPlayerEvents.count();
  console.log(`Toplam: ${eventsCount} kayıt`);

  const events = await prisma.matchPlayerEvents.findMany({ take: 10 });
  console.table(events);

  // 17. Official Roles
  console.log('\n👔 HAKEM ROLLERİ (OfficialRoles)');
  console.log('----------------------------------------');
  const officialRoles = await prisma.officialRole.findMany();
  console.log(`Toplam: ${officialRoles.length} kayıt`);
  console.table(officialRoles);

  // 18. Match Officials
  console.log('\n🚨 MAÇ HAKEMLERİ (MatchOfficials)');
  console.log('----------------------------------------');
  const officialsCount = await prisma.matchOfficial.count();
  console.log(`Toplam: ${officialsCount} kayıt`);

  const officials = await prisma.matchOfficial.findMany({ take: 10 });
  console.table(officials);

  // 19. App Settings
  console.log('\n⚙️ UYGULAMA AYARLARI (AppSettings)');
  console.log('----------------------------------------');
  const settings = await prisma.appSetting.findMany();
  console.log(`Toplam: ${settings.length} kayıt`);
  console.table(settings);

  // 20. Translations
  console.log('\n🌐 ÇEVRİLER (Translations)');
  console.log('----------------------------------------');
  const translationsCount = await prisma.translation.count();
  console.log(`Toplam: ${translationsCount} kayıt`);

  const translations = await prisma.translation.findMany({ take: 10 });
  console.table(translations);

  // Summary
  console.log('\n========================================');
  console.log('📊 ÖZET');
  console.log('========================================');
  console.log(`Ülkeler: ${await prisma.country.count()}`);
  console.log(`Ligler: ${await prisma.league.count()}`);
  console.log(`Takımlar: ${await prisma.team.count()}`);
  console.log(`Oyuncular: ${await prisma.player.count()}`);
  console.log(`Maçlar: ${await prisma.match.count()}`);
  console.log(`Canlı Maçlar: ${await prisma.liveMatch.count()}`);
  console.log(`AI Özellikleri: ${await prisma.matchAiFeature.count()}`);
  console.log(`Oran Kategorileri: ${await prisma.oddCategory.count()}`);
  console.log(`Oran Seçenekleri: ${await prisma.oddSelection.count()}`);
  console.log(`Tahminler: ${await prisma.prediction.count()}`);
  console.log(`AI Log: ${await prisma.aiPredictionsLog.count()}`);
  console.log(`Kullanıcılar: ${await prisma.user.count()}`);
  console.log(`Kuponlar: ${await prisma.userCoupon.count()}`);
  console.log(`Takım İstatistikleri: ${await prisma.matchTeamStats.count()}`);
  console.log(
    `Oyuncu İstatistikleri: ${await prisma.matchPlayerStats.count()}`,
  );
  console.log(`Olaylar: ${await prisma.matchPlayerEvents.count()}`);
  console.log(`Hakemler: ${await prisma.matchOfficial.count()}`);
  console.log(`Çeviriler: ${await prisma.translation.count()}`);
  console.log('========================================\n');

  await prisma.$disconnect();
}

inspectDatabase().catch((e) => {
  console.error('Hata:', e);
  process.exit(1);
});
