const router = require('express').Router();
const prisma = require('../config/db');
const { requireAuth, requireRole } = require('../middleware/auth');

// GET /api/products — 판매 중인 상품 목록
router.get('/', async (req, res) => {
  try {
    const page  = Math.max(1, parseInt(req.query.page) || 1);
    const limit = Math.min(50, parseInt(req.query.limit) || 20);
    const skip  = (page - 1) * limit;

    const sortMap = {
      'newest':    { createdAt: 'desc' },
      'popular':   { totalSales: 'desc' },
      'price_asc': { price: 'asc' },
      'price_desc':{ price: 'desc' },
    };
    const orderBy = sortMap[req.query.sort] || sortMap.newest;

    const [products, total] = await Promise.all([
      prisma.product.findMany({
        where: { isOnSale: true, project: { status: 'approved' } },
        skip, take: limit, orderBy,
        include: {
          project: {
            select: {
              id: true, title: true, description: true, difficultyLevel: true,
              user: { select: { nickname: true } },
              files: { where: { fileType: 'image' }, take: 1, orderBy: { displayOrder: 'asc' } },
            },
          },
          reviews: { where: { isVisible: true }, select: { rating: true } },
        },
      }),
      prisma.product.count({ where: { isOnSale: true, project: { status: 'approved' } } }),
    ]);

    // 평점 계산
    const enriched = products.map(p => ({
      ...p,
      avgRating: p.reviews.length
        ? +(p.reviews.reduce((s, r) => s + r.rating, 0) / p.reviews.length).toFixed(1)
        : null,
      reviewCount: p.reviews.length,
      reviews: undefined,
    }));

    res.json({ products: enriched, total, page, pages: Math.ceil(total / limit) });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '서버 오류' });
  }
});

// GET /api/products/:id — 상품 상세
router.get('/:id', async (req, res) => {
  try {
    const product = await prisma.product.findUnique({
      where: { id: req.params.id },
      include: {
        project: {
          include: {
            user: { select: { nickname: true } },
            files: { orderBy: { displayOrder: 'asc' } },
          },
        },
        reviews: {
          where: { isVisible: true },
          orderBy: { createdAt: 'desc' },
          take: 20,
          include: {
            user: { select: { nickname: true } },
            media: true,
          },
        },
      },
    });
    if (!product) return res.status(404).json({ error: '상품을 찾을 수 없습니다' });

    const avgRating = product.reviews.length
      ? +(product.reviews.reduce((s, r) => s + r.rating, 0) / product.reviews.length).toFixed(1)
      : null;

    res.json({ ...product, avgRating, reviewCount: product.reviews.length });
  } catch (err) {
    res.status(500).json({ error: '서버 오류' });
  }
});

// PUT /api/products/:id/toggle — 판매 일시중지/재개
router.put('/:id/toggle', requireAuth, async (req, res) => {
  try {
    const product = await prisma.product.findUnique({
      where: { id: req.params.id },
      include: { project: { select: { userId: true } } },
    });
    if (!product) return res.status(404).json({ error: '상품을 찾을 수 없습니다' });

    const isOwner = product.project.userId === req.user.id;
    if (!isOwner && req.user.role !== 'admin') {
      return res.status(403).json({ error: '권한이 없습니다' });
    }

    const updated = await prisma.product.update({
      where: { id: req.params.id },
      data: { isOnSale: !product.isOnSale },
    });
    res.json(updated);
  } catch (err) {
    res.status(500).json({ error: '서버 오류' });
  }
});

module.exports = router;
