import { Router, Request } from 'express';
import { CertificateService } from '../../services/CertificateService';
import { requireTraceContext } from '../../core/guards/trace-context.guard';
import { requirePermission } from '../../core/guards/rbac.guard';
import { logger } from '../../utils/logger';
import { CertificateStatus, CertificateType } from '../../models/Certificate';

const router = Router();

/**
 * [FE-COM001] 证书管理 API
 */

router.get('/certificates', requireTraceContext, requirePermission('certificate:read'), async (req, res) => {
  try {
    const traceContext = (req as any).traceContext!;
    const { tenantId, shopId, traceId } = traceContext;
    const { status, type, page = 1, pageSize = 10 } = req.query;

    const result = await CertificateService.query({
      tenantId,
      shopId,
      status: status as CertificateStatus,
      certificateType: type as CertificateType,
      page: parseInt(page as string),
      pageSize: parseInt(pageSize as string)
    });

    res.json({
      success: true,
      data: result.data,
      total: result.total,
      page: parseInt(page as string),
      pageSize: parseInt(pageSize as string)
    });
  } catch (error) {
    logger.error('[CertificateRoutes] GET /certificates error:', error);
    res.status(500).json({
      success: false,
      error: '获取证书列表失败'
    });
  }
});

router.get('/certificates/:id', requireTraceContext, requirePermission('certificate:read'), async (req, res) => {
  try {
    const traceContext = (req as any).traceContext!;
    const { tenantId, traceId } = traceContext;
    const id = req.params.id as string;

    const certificate = await CertificateService.getById(tenantId, id);

    if (!certificate) {
      return res.status(404).json({
        success: false,
        error: '证书不存在'
      });
    }

    res.json({
      success: true,
      data: certificate
    });
  } catch (error) {
    logger.error('[CertificateRoutes] GET /certificates/:id error:', error);
    res.status(500).json({
      success: false,
      error: '获取证书详情失败'
    });
  }
});

router.post('/certificates', requireTraceContext, requirePermission('certificate:create'), async (req, res) => {
  try {
    const traceContext = (req as any).traceContext!;
    const { tenantId, shopId, traceId } = traceContext;
    const certificateData = req.body;

    const id = await CertificateService.create({
      ...certificateData,
      tenantId,
      shopId,
      traceId
    });

    res.json({
      success: true,
      data: { id }
    });
  } catch (error) {
    logger.error('[CertificateRoutes] POST /certificates error:', error);
    res.status(500).json({
      success: false,
      error: '创建证书失败'
    });
  }
});

router.put('/certificates/:id', requireTraceContext, requirePermission('certificate:update'), async (req, res) => {
  try {
    const traceContext = (req as any).traceContext!;
    const { tenantId, shopId, traceId } = traceContext;
    const id = req.params.id as string;
    const certificateData = req.body;

    await CertificateService.update(tenantId, id, {
      ...certificateData,
      tenantId,
      shopId,
      traceId
    }, traceId);

    res.json({
      success: true
    });
  } catch (error) {
    logger.error('[CertificateRoutes] PUT /certificates/:id error:', error);
    res.status(500).json({
      success: false,
      error: '更新证书失败'
    });
  }
});

router.delete('/certificates/:id', requireTraceContext, requirePermission('certificate:delete'), async (req, res) => {
  try {
    const traceContext = (req as any).traceContext!;
    const { tenantId, traceId } = traceContext;
    const id = req.params.id as string;

    await CertificateService.delete(tenantId, id, traceId);

    res.json({
      success: true
    });
  } catch (error) {
    logger.error('[CertificateRoutes] DELETE /certificates/:id error:', error);
    res.status(500).json({
      success: false,
      error: '删除证书失败'
    });
  }
});

router.put('/certificates/:id/status', requireTraceContext, requirePermission('certificate:approve'), async (req, res) => {
  try {
    const traceContext = (req as any).traceContext!;
    const { tenantId, traceId } = traceContext;
    const id = req.params.id as string;
    const { status, approvedBy } = req.body;

    await CertificateService.updateStatus(tenantId, id, status as CertificateStatus, traceId);

    res.json({
      success: true
    });
  } catch (error) {
    logger.error('[CertificateRoutes] PUT /certificates/:id/status error:', error);
    res.status(500).json({
      success: false,
      error: '更新证书状态失败'
    });
  }
});

export default router;
