/**
 * image-cleanup.js — 定时清理过期图片
 *
 * - 每小时运行一次
 * - 删除 30 天以上的图片记录和文件
 * - 删除 24 小时以上未关联 session 的孤儿图片
 * - 删文件前检查同 hash 是否还有其他引用（去重安全）
 */

import { imageDb } from '../database/db.js';
import { deleteImageFile } from './image-storage.js';

const CLEANUP_INTERVAL_MS = 60 * 60 * 1000; // 1 hour
const RETENTION_DAYS = 30;
const ORPHAN_HOURS = 24;

let cleanupInterval = null;

export function startImageCleanup() {
  console.log('[ImageCleanup] Starting image cleanup service');

  // Initial cleanup after 30s
  setTimeout(() => runCleanup(), 30000);

  // Schedule periodic cleanup
  cleanupInterval = setInterval(() => runCleanup(), CLEANUP_INTERVAL_MS);
  console.log(`[ImageCleanup] Scheduled to run every ${CLEANUP_INTERVAL_MS / 1000 / 60} minutes`);
}

export function stopImageCleanup() {
  if (cleanupInterval) {
    clearInterval(cleanupInterval);
    cleanupInterval = null;
  }
}

async function runCleanup() {
  try {
    let deletedFiles = 0;
    let deletedRecords = 0;

    // 1. Clean expired images (>30 days)
    const expiredImages = imageDb.getExpiredImages(RETENTION_DAYS);
    if (expiredImages.length > 0) {
      const expiredIds = expiredImages.map(img => img.id);

      // Delete files only when no other records reference the same hash
      for (const img of expiredImages) {
        const otherRefs = imageDb.countByHash(img.user_uuid, img.file_hash, expiredIds);
        if (otherRefs === 0) {
          await deleteImageFile(img.user_uuid, img.file_hash, img.file_ext);
          deletedFiles++;
        }
      }

      imageDb.deleteImagesByIds(expiredIds);
      deletedRecords += expiredIds.length;
    }

    // 2. Clean orphaned uploads (session_id IS NULL, >24h)
    const orphaned = imageDb.deleteOrphanedImages(ORPHAN_HOURS);
    if (orphaned.length > 0) {
      for (const img of orphaned) {
        const otherRefs = imageDb.countByHash(img.user_uuid, img.file_hash, [img.id]);
        if (otherRefs === 0) {
          await deleteImageFile(img.user_uuid, img.file_hash, img.file_ext);
          deletedFiles++;
        }
      }
      deletedRecords += orphaned.length;
    }

    if (deletedRecords > 0) {
      console.log(`[ImageCleanup] Cleaned up ${deletedRecords} records, ${deletedFiles} files`);
    }
  } catch (error) {
    console.error('[ImageCleanup] Error during cleanup:', error);
  }
}
