/**
 * Subscription Audit Log Routes
 * Super Admin only — view audit logs for subscription actions.
 */

import express, { Request, Response } from 'express';
import { authenticate, requireRole } from '../middleware/auth';
import { getModels } from '../models';

const router = express.Router();

// All routes require super-admin
router.use(authenticate, requireRole('super-admin'));

// GET /company/:companyId — Get audit logs for a company
router.get('/company/:companyId', async (req: Request, res: Response) => {
  try {
    const { SubscriptionAuditLog } = getModels();
    const { page = 1, limit = 50, action } = req.query;

    const filter: any = { companyId: req.params.companyId };
    if (action) filter.action = action;

    const logs = await SubscriptionAuditLog.find(filter)
      .sort({ createdAt: -1 })
      .skip((Number(page) - 1) * Number(limit))
      .limit(Number(limit))
      .lean();

    const total = await SubscriptionAuditLog.countDocuments(filter);

    res.json({
      logs,
      pagination: {
        page: Number(page),
        limit: Number(limit),
        total,
        pages: Math.ceil(total / Number(limit)),
      },
    });
  } catch (error) {
    console.error('Error fetching audit logs:', error);
    res.status(500).json({ error: 'Failed to fetch audit logs' });
  }
});

export default router;