const express = require('express');
const prisma = require('../lib/prisma');
const { adminAuthMiddleware } = require('../lib/auth');

const router = express.Router();

// 获取待审核列表
router.get('/reviews', adminAuthMiddleware, async (req, res) => {
  try {
    const { status } = req.query;
    // 分页参数校验：默认 page=1, pageSize=20，限制最大 100
    const page = Math.max(1, Math.floor(Number(req.query.page) || 1));
    const pageSize = Math.min(100, Math.max(1, Math.floor(Number(req.query.pageSize) || 20)));
    if (Number.isNaN(page) || Number.isNaN(pageSize)) {
      return res.status(400).json({ error: 'page 和 pageSize 必须为正整数' });
    }
    const where = status ? { reviewStatus: status } : { reviewStatus: 'pending_review' };

    const [roles, total] = await Promise.all([
      prisma.role.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * pageSize,
        take: pageSize,
        select: {
          id: true,
          displayName: true,
          creatorId: true,
          reviewStatus: true,
          reviewNote: true,
          qrCodeUrl: true,
          syncedAt: true,
          createdAt: true,
        },
      }),
      prisma.role.count({ where }),
    ]);

    res.json({ roles, total, page, pageSize });
  } catch (err) {
    console.error('获取审核列表失败:', err);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 获取角色详情（审核用）
router.get('/reviews/:roleId', adminAuthMiddleware, async (req, res) => {
  try {
    const role = await prisma.role.findUnique({
      where: { id: req.params.roleId },
    });
    if (!role) {
      return res.status(404).json({ error: '角色不存在' });
    }
    res.json({ role });
  } catch (err) {
    console.error('获取角色详情失败:', err);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 通过审核
router.post('/reviews/:roleId/approve', adminAuthMiddleware, async (req, res) => {
  try {
    const role = await prisma.role.findUnique({ where: { id: req.params.roleId } });
    if (!role) {
      return res.status(404).json({ error: '角色不存在' });
    }
    if (role.reviewStatus !== 'pending_review') {
      return res.status(400).json({ error: `当前状态为 ${role.reviewStatus}，无法通过审核` });
    }

    const updated = await prisma.role.update({
      where: { id: req.params.roleId },
      data: { reviewStatus: 'approved' },
      select: { id: true, displayName: true, reviewStatus: true },
    });
    res.json({ role: updated });
  } catch (err) {
    console.error('通过审核失败:', err);
    res.status(500).json({ error: '操作失败' });
  }
});

// 驳回审核
router.post('/reviews/:roleId/reject', adminAuthMiddleware, async (req, res) => {
  try {
    const { reviewNote } = req.body;
    const role = await prisma.role.findUnique({ where: { id: req.params.roleId } });
    if (!role) {
      return res.status(404).json({ error: '角色不存在' });
    }
    if (role.reviewStatus !== 'pending_review') {
      return res.status(400).json({ error: `当前状态为 ${role.reviewStatus}，无法驳回` });
    }

    const updated = await prisma.role.update({
      where: { id: req.params.roleId },
      data: { reviewStatus: 'rejected', reviewNote: reviewNote || null },
      select: { id: true, displayName: true, reviewStatus: true, reviewNote: true },
    });
    res.json({ role: updated });
  } catch (err) {
    console.error('驳回审核失败:', err);
    res.status(500).json({ error: '操作失败' });
  }
});

// 获取所有角色同步状态
router.get('/sync-status', adminAuthMiddleware, async (req, res) => {
  try {
    const roles = await prisma.role.findMany({
      where: { reviewStatus: { in: ['approved', 'syncing', 'synced', 'failed'] } },
      orderBy: { createdAt: 'desc' },
      select: {
        id: true,
        displayName: true,
        creatorId: true,
        reviewStatus: true,
        qrCodeUrl: true,
        syncedAt: true,
        createdAt: true,
      },
    });
    res.json({ roles });
  } catch (err) {
    console.error('获取同步状态失败:', err);
    res.status(500).json({ error: '服务器错误' });
  }
});

module.exports = router;
