import { Router } from 'express';
import { prisma } from '../../config/database.js';
import { requireAdmin, requireSuperAdmin } from '../../middleware/requireRole.js';
import { validate } from '../../middleware/validate.js';
import { updateSettingsSchema } from '../../validators/admin.js';
import { invalidateConfigCache } from '../../utils/moderation.js';

const router = Router();

// GET /api/admin/settings
router.get('/', requireAdmin, async (_req, res, next) => {
  try {
    let config = await prisma.platformConfig.findFirst();
    if (!config) {
      config = await prisma.platformConfig.create({ data: {} });
    }
    res.json(config);
  } catch (error) {
    next(error);
  }
});

// PATCH /api/admin/settings
router.patch('/', requireSuperAdmin, validate(updateSettingsSchema), async (req, res, next) => {
  try {
    let config = await prisma.platformConfig.findFirst();
    if (!config) {
      config = await prisma.platformConfig.create({ data: {} });
    }

    const updated = await prisma.platformConfig.update({
      where: { id: config.id },
      data: req.body,
    });

    invalidateConfigCache();
    res.json(updated);
  } catch (error) {
    next(error);
  }
});

export default router;
