import { Router } from 'express';
import { z } from 'zod';
import { pool } from '../db/connection.js';
import { requireAuth } from '../middleware/auth.js';

const router = Router();

router.post('/:dealId', requireAuth, async (req, res) => {
  try {
    const dealId = Number(req.params.dealId);
    
    // Input validation with Zod
    const reviewSchema = z.object({ 
      revieweeId: z.number().int().positive(), 
      rating: z.number().int().min(1).max(5), 
      comment: z.string().max(2000).optional() 
    });
    
    const parsed = reviewSchema.safeParse(req.body);

    if (!parsed.success || Number.isNaN(dealId)) {
      return res.status(400).json({ error: 'Invalid payload' });
    }

    const now = new Date();
    const earliest = new Date(now.getTime() + 2 * 24 * 60 * 60 * 1000);
    const latest = new Date(now.getTime() + 14 * 24 * 60 * 60 * 1000);

    const { revieweeId, rating, comment } = parsed.data;

    // Check if deal exists
    const [dealResult] = await pool.query(
      'SELECT id FROM deals WHERE id = ?',
      [dealId]
    );

    if (dealResult.length === 0) {
      return res.status(404).json({ error: 'Deal not found' });
    }

    // Check if user has already reviewed this deal
    const [existingReview] = await pool.query(
      'SELECT id FROM reviews WHERE deal_id = ? AND reviewer_id = ?',
      [dealId, req.user.userId]
    );

    if (existingReview.length > 0) {
      return res.status(409).json({ error: 'You have already reviewed this deal' });
    }

    const [result] = await pool.query(
      `INSERT INTO reviews (deal_id, reviewer_id, reviewee_id, rating, comment, earliest_prompt_at, latest_prompt_at)
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      [dealId, req.user.userId, revieweeId, rating, comment || null, earliest, latest]
    );

    res.status(201).json({ id: result.insertId });
  } catch (error) {
    console.error('Error creating review:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

export default router;