import { prisma } from '../../config/database';
import { logger } from '../../utils/logger';

export const analyticsCleanupService = {
  async cleanupAll(): Promise<void> {
    // Read retention setting from SiteSettings
    let retentionDays = 90;
    try {
      const settings = await prisma.siteSettings.findFirst();
      if (settings?.analyticsRetentionDays) {
        retentionDays = settings.analyticsRetentionDays;
      }
    } catch {
      // Use default if settings unavailable
    }

    const cutoff = new Date();
    cutoff.setDate(cutoff.getDate() - retentionDays);

    const [docsDeleted, videoDeleted, photoDeleted] = await Promise.all([
      prisma.docsPageView.deleteMany({ where: { createdAt: { lt: cutoff } } }),
      prisma.videoView.deleteMany({ where: { createdAt: { lt: cutoff } } }),
      prisma.photoView.deleteMany({ where: { viewedAt: { lt: cutoff } } }),
    ]);

    const total = docsDeleted.count + videoDeleted.count + photoDeleted.count;
    if (total > 0) {
      logger.info(`Analytics cleanup: removed ${total} records older than ${retentionDays} days`, {
        docs: docsDeleted.count,
        video: videoDeleted.count,
        photo: photoDeleted.count,
      });
    }
  },
};
