import { Router, Request, Response } from 'express';
import { fetchSales, isConfigured } from '../services/erpClient';

const router = Router();

// GET /api/erp/sales?startDate=2025-01-01T00:00:00&endDate=2025-01-31T00:00:00
router.get('/sales', async (req: Request, res: Response) => {
  if (!isConfigured()) {
    res.status(503).json({ error: 'ERP API not configured on server' });
    return;
  }

  const { startDate, endDate } = req.query;

  if (!startDate || !endDate) {
    res.status(400).json({ error: 'startDate and endDate query params required' });
    return;
  }

  try {
    const data = await fetchSales(startDate as string, endDate as string);
    res.json(data);
  } catch (err) {
    console.error('ERP fetch error:', (err as Error).message);
    res.status(502).json({ error: 'Failed to fetch from ERP API', details: (err as Error).message });
  }
});

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

export default router;
