import { Router, Request, Response } from 'express';
import { AuditAction } from '@prisma/client';
import { prisma } from '../../lib/prisma';
import { authenticate, requireRole } from '../../middleware/auth';
const router = Router();

router.use(authenticate);

router.get('/', requireRole('SUPER_ADMIN', 'OPERATOR'), async (_req: Request, res: Response) => {
  const settings = await prisma.ccpSetting.findMany();
  const map: Record<string, unknown> = {};
  for (const s of settings) {
    map[s.key] = s.value;
  }
  res.json({ data: map });
});

router.put(
  '/:key',
  requireRole('SUPER_ADMIN'),
  async (req: Request, res: Response) => {
    const { key } = req.params as { key: string };
    const { value } = req.body;
    const setting = await prisma.ccpSetting.upsert({
      where: { key },
      update: { value },
      create: { key, value },
    });

    await prisma.auditLog.create({
      data: {
        userId: req.user!.id,
        action: AuditAction.SETTINGS_UPDATE,
        details: { key, value },
        ipAddress: req.ip,
      },
    });

    res.json({ data: setting });
  }
);

export default router;
