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

const prisma = new PrismaClient();

async function cleanupCompletedProgress() {
  console.log('🧹 Cleaning up progress data for completed videos...');

  try {
    // Find all completed video progress records
    const completedProgress = await prisma.videoProgress.findMany({
      where: { completed: true },
      select: { id: true, userId: true, videoId: true },
    });

    console.log(`📊 Found ${completedProgress.length} completed videos`);

    if (completedProgress.length === 0) {
      console.log('✅ No completed videos to clean up');
      return;
    }

    let totalSegmentsDeleted = 0;

    // For each completed video, delete its watch segments
    // (we keep the VideoProgress record for history, but clean up the granular segment data)
    for (const progress of completedProgress) {
      const deletedSegments = await prisma.videoWatchSegment.deleteMany({
        where: {
          userId: progress.userId,
          videoId: progress.videoId,
        },
      });

      totalSegmentsDeleted += deletedSegments.count;

      if (deletedSegments.count > 0) {
        console.log(
          `  ✓ Deleted ${deletedSegments.count} segments for video ${progress.videoId}`
        );
      }
    }

    console.log(`\n📈 Cleanup Summary:`);
    console.log(`  - Completed videos processed: ${completedProgress.length}`);
    console.log(`  - Watch segments deleted: ${totalSegmentsDeleted}`);
    console.log(`✅ Cleanup complete!`);

  } catch (err: any) {
    console.error('❌ Error during cleanup:', err.message);
    throw err;
  } finally {
    await prisma.$disconnect();
  }
}

cleanupCompletedProgress().catch((err) => {
  console.error('Fatal error:', err);
  process.exit(1);
});
