const router = require('express').Router();
const { query } = require('express-validator');
const prisma = require('../lib/prisma');
const { validateRequest } = require('../middleware/errorHandler');

// GET /api/audit-logs?tableName=&recordId=&limit=&offset= — query logs
router.get(
  '/',
  [
    query('tableName').optional().isIn(['experiments', 'animals', 'daily_statuses', 'audit_logs']).withMessage('tableName must be one of: experiments, animals, daily_statuses, audit_logs'),
    query('recordId').optional().matches(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i).withMessage('recordId must be a valid UUID'),
    query('limit').optional().isInt({ min: 1, max: 200 }).withMessage('limit must be 1–200').toInt(),
    query('offset').optional().isInt({ min: 0 }).withMessage('offset must be ≥0').toInt(),
  ],
  validateRequest,
  async (req, res, next) => {
    try {
      const { tableName, recordId } = req.query;
      const limit = req.query.limit || 50;
      const offset = req.query.offset || 0;

      const where = {};
      if (tableName) where.table_name = tableName;
      if (recordId) where.record_id = recordId;

      const [logs, total] = await Promise.all([
        prisma.auditLog.findMany({
          where,
          orderBy: { timestamp: 'desc' },
          take: limit,
          skip: offset,
        }),
        prisma.auditLog.count({ where }),
      ]);

      res.json({ logs, total, limit, offset });
    } catch (err) {
      next(err);
    }
  }
);

// GET /api/audit-logs/:id — single log entry
router.get('/:id', async (req, res, next) => {
  try {
    const log = await prisma.auditLog.findUnique({ where: { id: req.params.id } });
    if (!log) return res.status(404).json({ error: 'Audit log not found' });
    res.json(log);
  } catch (err) {
    next(err);
  }
});

module.exports = router;
