import { Router } from 'express';
import pool from '../db';

const router = Router();

// GET /api/sync/status
router.get('/status', async (_req, res) => {
  try {
    const states = await pool.query(`
      SELECT ss.*,
        pg_size_pretty(ss.last_byte::bigint) as file_size_human
      FROM crm_sync_state ss
      ORDER BY ss.agent, ss.source_file
    `);

    // Summary
    const summary = await pool.query(`
      SELECT agent,
        COUNT(*) as files,
        SUM(last_line) as total_lines,
        SUM(last_byte) as total_bytes,
        MAX(last_synced) as last_synced
      FROM crm_sync_state
      GROUP BY agent
      ORDER BY agent
    `);

    res.json({
      files: states.rows,
      summary: summary.rows,
    });
  } catch (err: any) {
    console.error('Sync status error:', err);
    res.status(500).json({ error: err.message });
  }
});

// POST /api/sync/trigger — force re-sync (resets byte offsets)
router.post('/trigger', async (req, res) => {
  try {
    const { agent, full } = req.body;

    if (full) {
      // Reset all sync state for full re-import
      if (agent) {
        await pool.query('DELETE FROM crm_sync_state WHERE agent = $1', [agent]);
      } else {
        await pool.query('DELETE FROM crm_sync_state');
      }
      res.json({ message: 'Sync state reset. Next worker run will do a full import.' });
    } else {
      // Just update timestamps to trigger worker
      if (agent) {
        await pool.query("UPDATE crm_sync_state SET status = 'pending' WHERE agent = $1", [agent]);
      } else {
        await pool.query("UPDATE crm_sync_state SET status = 'pending'");
      }
      res.json({ message: 'Sync triggered for next worker run.' });
    }
  } catch (err: any) {
    console.error('Sync trigger error:', err);
    res.status(500).json({ error: err.message });
  }
});

export default router;
