'use strict';

const express = require('express');

// Отдельный requireAdmin для API — возвращает JSON вместо plain text
function apiRequireAdmin(req, res, next) {
  if (!req.user || !req.user.isAdmin) {
    return res.status(403).json({ error: 'Admin role required' });
  }
  next();
}

function createAdminRouter({ q }) {
  const router = express.Router();
  const json = express.json({ limit: '8kb' });

  // GET /api/v1/companies — все компании (admin only)
  router.get('/companies', apiRequireAdmin, async (req, res) => {
    try {
      const companies = await q.getAllCompanies();
      res.json({ companies });
    } catch (e) {
      res.status(500).json({ error: e.message });
    }
  });

  // PATCH /api/v1/companies/:id/limit — установить лимит (admin only)
  router.patch('/companies/:id/limit', apiRequireAdmin, json, async (req, res) => {
    const rawLimit = (req.body || {}).limit;
    const isReset = rawLimit === null || rawLimit === undefined;
    const limit = isReset ? null : parseInt(rawLimit, 10);
    if (!isReset && (isNaN(limit) || limit < 0)) {
      return res.status(400).json({ error: 'limit must be non-negative integer or null to reset' });
    }
    try {
      await q.setLimit(req.params.id, limit);
      res.json({ ok: true, limit });
    } catch (e) {
      res.status(e.status || 500).json({ error: e.message });
    }
  });

  // GET /api/v1/audit — журнал действий (admin only)
  // ?company=<id> — фильтр по компании (опционально)
  router.get('/audit', apiRequireAdmin, async (req, res) => {
    try {
      const companyId = req.query.company ? parseInt(req.query.company, 10) : null;
      const [rows, companies] = await Promise.all([
        q.getAudit(companyId && Number.isFinite(companyId) ? companyId : null),
        q.getAllCompanies(),
      ]);
      res.json({ rows, companies });
    } catch (e) {
      res.status(500).json({ error: e.message });
    }
  });

  return router;
}

module.exports = { createAdminRouter };
