import { Router, Request, Response } from 'express';
import { isDatabaseConnected } from '../config/database';
import GenerationHistoryModel from '../models/GenerationHistory';

const router = Router();

router.get('/', async (_req: Request, res: Response): Promise<void> => {
  if (!isDatabaseConnected()) {
    res.json({ history: [], dbAvailable: false });
    return;
  }
  try {
    const history = await GenerationHistoryModel.find()
      .sort({ createdAt: -1 })
      .limit(50)
      .select('-outputJson');
    res.json({ history, dbAvailable: true });
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch history.' });
  }
});

router.get('/:id/json', async (req: Request, res: Response): Promise<void> => {
  if (!isDatabaseConnected()) {
    res.status(503).json({ error: 'Database not available.' });
    return;
  }
  try {
    const item = await GenerationHistoryModel.findById(req.params.id).select('outputJson');
    if (!item) {
      res.status(404).json({ error: 'History item not found.' });
      return;
    }
    res.json({ template: item.outputJson });
  } catch {
    res.status(500).json({ error: 'Failed to fetch history item.' });
  }
});

router.delete('/:id', async (req: Request, res: Response): Promise<void> => {
  if (!isDatabaseConnected()) {
    res.status(503).json({ error: 'Database not available.' });
    return;
  }
  try {
    await GenerationHistoryModel.findByIdAndDelete(req.params.id);
    res.json({ success: true });
  } catch {
    res.status(500).json({ error: 'Failed to delete history item.' });
  }
});

export default router;
