import { Router } from 'express';
import { prisma } from '../config/database.js';
import { authenticate } from '../middleware/auth.js';
import { validate } from '../middleware/validate.js';
import { createReportSchema } from '../validators/report.js';

const router = Router();

// POST /api/reports - Create report
router.post('/', authenticate, validate(createReportSchema), async (req, res, next) => {
  try {
    const { targetType, targetId, reason, description } = req.body;

    // Verify target exists
    if (targetType === 'LISTING') {
      const listing = await prisma.listing.findUnique({ where: { id: targetId } });
      if (!listing) {
        res.status(404).json({ message: 'Listing not found' });
        return;
      }
    } else {
      const user = await prisma.user.findUnique({ where: { id: targetId } });
      if (!user) {
        res.status(404).json({ message: 'User not found' });
        return;
      }
    }

    const report = await prisma.report.create({
      data: {
        reporterId: req.userId!,
        targetType,
        targetId,
        reason,
        description,
      },
    });

    res.status(201).json(report);
  } catch (error) {
    next(error);
  }
});

export default router;
