import { Router, Request, Response } from 'express';
import { etl } from '../config';
import { runSync } from '../services/etlSync';

const router = Router();

// POST /api/etl/sync?mode=full|incremental
router.post('/sync', async (req: Request, res: Response) => {
  // Auth check
  const auth = req.headers.authorization;
  if (etl.secret && auth !== `Bearer ${etl.secret}`) {
    res.status(401).json({ error: 'Unauthorized' });
    return;
  }

  const mode = (req.query.mode as string) === 'full' ? 'full' : 'incremental';

  try {
    console.log(`\nETL sync started (${mode})...`);
    const result = await runSync(mode);
    console.log(`ETL sync complete: ${result.transactionsFetched} transactions → ${result.recordsWritten} records in ${result.duration}`);
    res.json(result);
  } catch (err) {
    console.error('ETL sync failed:', (err as Error).message);
    res.status(500).json({ error: 'ETL sync failed', details: (err as Error).message });
  }
});

// GET /api/etl/status
router.get('/status', (_req: Request, res: Response) => {
  res.json({ configured: !!etl.secret });
});

export default router;
