const router = require('express').Router();
const { v4: uuidv4 } = require('uuid');
const prisma = require('../config/db');
const { requireAuth, requireRole } = require('../middleware/auth');
const { writeAuditLog } = require('../middleware/audit');

// POST /api/orders — 주문 생성 (결제 전)
router.post('/', requireAuth, async (req, res) => {
  const { productId } = req.body;
  if (!productId) return res.status(400).json({ error: 'productId가 필요합니다' });

  try {
    const product = await prisma.product.findUnique({
      where: { id: productId },
      include: { project: { select: { commissionRate: true, userId: true } } },
    });
    if (!product) return res.status(404).json({ error: '상품을 찾을 수 없습니다' });
    if (!product.isOnSale) return res.status(400).json({ error: '판매 중지된 상품입니다' });
    if (product.project.userId === req.user.id) return res.status(400).json({ error: '자신의 상품은 구매할 수 없습니다' });

    // 이미 유효한 주문이 있는지 확인 (중복 구매 방지)
    const existing = await prisma.order.findFirst({
      where: { buyerId: req.user.id, productId, status: { in: ['pending', 'paid'] } },
      include: { flashToken: true },
    });
    if (existing?.status === 'paid') {
      return res.status(409).json({
        error: '이미 구매한 상품입니다',
        flashToken: existing.flashToken?.token,
        orderId: existing.id,
      });
    }
    if (existing?.status === 'pending') {
      return res.json({ orderId: existing.id, amount: existing.amount, status: 'pending' });
    }

    const commissionAmount = Math.round(product.price * product.project.commissionRate);
    const sellerAmount     = product.price - commissionAmount;

    const order = await prisma.order.create({
      data: {
        buyerId:          req.user.id,
        productId,
        amount:           product.price,
        commissionAmount,
        sellerAmount,
        paymentGateway:   'toss',
        tossOrderId:      `mock_${uuidv4()}`,
        buyerInfo:        { email: req.user.email, nickname: req.user.nickname },
        deviceInfo:       { ip: req.ip, userAgent: req.headers['user-agent'] },
      },
    });

    await writeAuditLog({ userId: req.user.id, action: 'ORDER_CREATE', targetType: 'Order', targetId: order.id, req, responseStatus: 201 });
    res.status(201).json({ orderId: order.id, amount: order.amount, status: 'pending' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '서버 오류' });
  }
});

// POST /api/orders/:id/mock-pay — 모의 결제 (사업자 등록 전 테스트용)
// 실제 결제 없이 즉시 paid 처리하고 FlashToken 발급
router.post('/:id/mock-pay', requireAuth, async (req, res) => {
  try {
    const order = await prisma.order.findUnique({
      where: { id: req.params.id },
      include: { flashToken: true },
    });
    if (!order) return res.status(404).json({ error: '주문을 찾을 수 없습니다' });
    if (order.buyerId !== req.user.id) return res.status(403).json({ error: '권한이 없습니다' });
    if (order.status === 'paid') {
      return res.json({ flashToken: order.flashToken?.token, orderId: order.id, alreadyPaid: true });
    }
    if (order.status !== 'pending') {
      return res.status(400).json({ error: `${order.status} 상태의 주문은 결제할 수 없습니다` });
    }

    const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); // 30일

    const [updatedOrder, flashToken] = await prisma.$transaction([
      prisma.order.update({
        where: { id: order.id },
        data: { status: 'paid', paidAt: new Date(), paymentKey: `mock_${uuidv4()}` },
      }),
      prisma.flashToken.create({
        data: { orderId: order.id, expiresAt },
      }),
      prisma.product.update({
        where: { id: order.productId },
        data: { totalSales: { increment: 1 } },
      }),
    ]);

    await writeAuditLog({
      userId: req.user.id, action: 'MOCK_PAYMENT',
      targetType: 'Order', targetId: order.id,
      req, metadata: { amount: order.amount, mode: 'mock' }, responseStatus: 200,
    });

    res.json({ flashToken: flashToken.token, orderId: order.id, expiresAt: flashToken.expiresAt });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '서버 오류' });
  }
});

// GET /api/orders/me — 내 주문 목록
router.get('/me', requireAuth, async (req, res) => {
  try {
    const orders = await prisma.order.findMany({
      where: { buyerId: req.user.id },
      orderBy: { orderedAt: 'desc' },
      include: {
        product: {
          select: {
            id: true, price: true,
            project: { select: { title: true, chipFamily: true, files: { where: { fileType: 'image' }, take: 1 } } },
          },
        },
        flashToken: { select: { token: true, isUsed: true, expiresAt: true } },
        review: { select: { id: true } },
      },
    });
    res.json(orders);
  } catch (err) {
    res.status(500).json({ error: '서버 오류' });
  }
});

// GET /api/orders/:id
router.get('/:id', requireAuth, async (req, res) => {
  try {
    const order = await prisma.order.findUnique({
      where: { id: req.params.id },
      include: {
        product: { include: { project: true } },
        flashToken: true,
      },
    });
    if (!order) return res.status(404).json({ error: '주문을 찾을 수 없습니다' });
    if (order.buyerId !== req.user.id && req.user.role !== 'admin') {
      return res.status(403).json({ error: '권한이 없습니다' });
    }
    res.json(order);
  } catch (err) {
    res.status(500).json({ error: '서버 오류' });
  }
});

// POST /api/orders/:id/refund — 환불 (모의 / 플래시 미완료 시만)
router.post('/:id/refund', requireAuth, async (req, res) => {
  try {
    const order = await prisma.order.findUnique({
      where: { id: req.params.id },
      include: { flashToken: true },
    });
    if (!order) return res.status(404).json({ error: '주문을 찾을 수 없습니다' });
    if (order.buyerId !== req.user.id && req.user.role !== 'admin') {
      return res.status(403).json({ error: '권한이 없습니다' });
    }
    if (order.status !== 'paid') return res.status(400).json({ error: '결제 완료 상태가 아닙니다' });
    if (order.flashToken?.isUsed && req.user.role !== 'admin') {
      return res.status(400).json({ error: '플래시가 완료된 주문은 환불할 수 없습니다' });
    }

    await prisma.$transaction([
      prisma.order.update({
        where: { id: order.id },
        data: { status: 'refunded', refundedAt: new Date(), refundReason: req.body.reason || '사용자 요청' },
      }),
      // FlashToken 무효화
      ...(order.flashToken ? [prisma.flashToken.update({
        where: { id: order.flashToken.id },
        data: { expiresAt: new Date() },
      })] : []),
      prisma.product.update({
        where: { id: order.productId },
        data: { totalSales: { decrement: 1 } },
      }),
    ]);

    await writeAuditLog({
      userId: req.user.id, action: 'REFUND',
      targetType: 'Order', targetId: order.id,
      req, responseStatus: 200,
    });
    res.json({ success: true });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '서버 오류' });
  }
});

module.exports = router;
