import { Router } from 'express';
import { prisma } from '../config/database.js';
import { authenticate } from '../middleware/auth.js';
import { getPlatformConfig } from '../utils/moderation.js';
import { AppError } from '../middleware/errorHandler.js';

const router = Router();

// POST /api/listings/:id/promote
router.post('/:id/promote', authenticate, async (req, res, next) => {
  try {
    const { days } = req.body;
    if (!days || days < 1 || days > 30) {
      throw new AppError(400, 'Days must be between 1 and 30');
    }

    const listing = await prisma.listing.findUnique({ where: { id: req.params.id } });
    if (!listing) throw new AppError(404, 'Listing not found');
    if (listing.sellerId !== req.userId) throw new AppError(403, 'Not authorized');
    if (listing.status !== 'ACTIVE') throw new AppError(400, 'Listing must be active');

    const config = await getPlatformConfig();
    const amountPaid = config.promotionDayPrice * days;

    const promotion = await prisma.promotedListing.upsert({
      where: { listingId: req.params.id },
      update: {
        endDate: new Date(Date.now() + days * 24 * 60 * 60 * 1000),
        amountPaid: { increment: amountPaid },
        isActive: true,
      },
      create: {
        listingId: req.params.id,
        userId: req.userId!,
        endDate: new Date(Date.now() + days * 24 * 60 * 60 * 1000),
        amountPaid,
        isActive: true,
      },
    });

    // Record payment
    await prisma.payment.create({
      data: {
        userId: req.userId!,
        listingId: req.params.id,
        amount: amountPaid,
        status: 'COMPLETED',
        type: 'PROMOTION',
        description: `${days}-day listing promotion`,
      },
    });

    res.json(promotion);
  } catch (error) {
    next(error);
  }
});

// GET /api/listings/:id/promotion
router.get('/:id/promotion', authenticate, async (req, res, next) => {
  try {
    const promotion = await prisma.promotedListing.findUnique({
      where: { listingId: req.params.id },
    });

    res.json(promotion || { isActive: false });
  } catch (error) {
    next(error);
  }
});

export default router;
