import cron from 'node-cron';
import { db } from '../../core/db.js';
import { copyFileSync, mkdirSync } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const BACKUP_DIR = path.join(__dirname, '..', '..', '..', 'data', 'backups');

export function startScheduler(client) {
  // Daily database backup at 3 AM
  cron.schedule('0 3 * * *', () => {
    try {
      mkdirSync(BACKUP_DIR, { recursive: true });
      const timestamp = new Date().toISOString().split('T')[0]; // YYYY-MM-DD
      const backupPath = path.join(BACKUP_DIR, `bot-${timestamp}.db`);
      const dbPath = path.join(__dirname, '..', '..', '..', 'data', 'bot.db');
      copyFileSync(dbPath, backupPath);
      console.log(`[backup] Created: ${backupPath}`);

      // Keep only last 7 days of backups (cleanup old ones)
      // TODO: implement cleanup logic
    } catch (e) {
      console.error('[backup] Failed:', e.message);
    }
  });

  // Expire pending orders >1h
  cron.schedule('*/15 * * * *', () => {
    const r = db.prepare(`
      UPDATE orders SET status = 'expired'
      WHERE status = 'pending' AND created_at < unixepoch() - 3600
    `).run();
    if (r.changes) console.log(`[scheduler] expired ${r.changes} pending orders`);
  });

  // Daily revenue report (at 23:55 server time)
  cron.schedule('55 23 * * *', () => {
    const stats = db.prepare(`
      SELECT COUNT(*) AS orders, IFNULL(SUM(total), 0) AS revenue
      FROM orders WHERE status = 'delivered' AND paid_at >= unixepoch() - 86400
    `).get();
    console.log(`[scheduler] daily report: ${stats.orders} orders · Rp${stats.revenue.toLocaleString('id-ID')}`);
  });

  // Stock low alert — owner DM every hour
  cron.schedule('0 * * * *', async () => {
    const lowStock = db.prepare(`
      SELECT p.id, p.name, p.guild_id,
        (SELECT COUNT(*) FROM stock WHERE product_id = p.id AND sold = 0) AS available
      FROM products p WHERE p.enabled = 1 AND p.auto_delivery = 1
      HAVING available < 3
    `).all();
    if (!lowStock.length) return;
    if (process.env.OWNER_ID) {
      try {
        const user = await client.users.fetch(process.env.OWNER_ID);
        await user.send({
          content: `⚠️ **Low stock alert**\n${lowStock.map(p => `• \`#${p.id}\` ${p.name} — ${p.available} left`).join('\n')}`,
        });
      } catch {}
    }
  });

  console.log('⏰ Scheduler started');
}
