import pool from '../db/pool.js';
import { deleteObject } from '../s3/client.js';

const CLEANUP_INTERVAL_MS = 3600_000;

let _interval = null;

async function cleanup() {
  const expired = await pool.query(
    'SELECT * FROM temp_segments WHERE expires_at < NOW()'
  );

  if (expired.rows.length === 0) return;

  let deleted = 0;
  let errors = 0;

  for (const segment of expired.rows) {
    try {
      await deleteObject(segment.s3_key);
      await pool.query('DELETE FROM temp_segments WHERE id = $1', [segment.id]);
      deleted++;
    } catch (err) {
      console.error('[cleanup] failed to delete segment ' + segment.id + ': ' + err.message);
      errors++;
    }
  }

  console.log(`[cleanup] temp segments: ${deleted} deleted, ${errors} errors`);
}

export function startCleanupLoop() {
  if (_interval) return;
  console.log(`[cleanup] temp segments loop started (interval=${CLEANUP_INTERVAL_MS}ms)`);
  cleanup().catch(() => {});
  _interval = setInterval(() => cleanup().catch(() => {}), CLEANUP_INTERVAL_MS);
}

export function stopCleanupLoop() {
  if (_interval) { clearInterval(_interval); _interval = null; }
}
