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

const router = Router();

// GET /help-requests - Fetch all help requests with requester names
router.get('/', async (_req, res) => {
  try {
    const [rows] = await pool.query(
      `SELECT hr.id, hr.title, hr.description, hr.value_chf, hr.status, hr.created_at, u.display_name requester_name
       FROM help_requests hr
       JOIN users u ON u.id = hr.requester_id
       ORDER BY hr.created_at DESC`
    );
    res.json(rows);
  } catch (error) {
    console.error('Error fetching help requests:', error);
    res.status(500).json({ error: 'Internal server error', details: error.message });
  }
});

// POST /help-requests - Create a new help request
router.post('/', requireAuth, requireIdempotencyKey, async (req, res) => {
  try {
    const parsed = z.object({
      title: z.string().min(3).max(180),
      description: z.string().min(5),
      valueChf: z.number().positive()
    }).safeParse(req.body);

    if (!parsed.success) {
      return res.status(400).json({ 
        error: 'Validation failed',
        details: parsed.error.flatten() 
      });
    }

    const { title, description, valueChf } = parsed.data;
    const [result] = await pool.query(
      'INSERT INTO help_requests (requester_id, title, description, value_chf) VALUES (?, ?, ?, ?)',
      [req.user.userId, title, description, valueChf]
    );

    // Cache the response for idempotent requests
    if (req.cacheIdempotentResponse) {
      await req.cacheIdempotentResponse(201, { id: result.insertId });
    }

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

// PUT /help-requests/:id - Update a help request
router.put('/:id', requireAuth, async (req, res) => {
  try {
    const { id } = req.params;
    const parsed = z.object({
      title: z.string().min(3).max(180),
      description: z.string().min(5),
      valueChf: z.number().positive(),
      status: z.enum(['open', 'in_progress', 'completed', 'cancelled']).optional()
    }).safeParse(req.body);

    if (!parsed.success) {
      return res.status(400).json({ 
        error: 'Validation failed',
        details: parsed.error.flatten() 
      });
    }

    const { title, description, valueChf, status } = parsed.data;
    
    // Check if the help request exists and belongs to the user
    const [existing] = await pool.query(
      'SELECT id FROM help_requests WHERE id = ? AND requester_id = ?',
      [id, req.user.userId]
    );

    if (existing.length === 0) {
      return res.status(404).json({ error: 'Help request not found or unauthorized' });
    }

    const [result] = await pool.query(
      'UPDATE help_requests SET title = ?, description = ?, value_chf = ?, status = ? WHERE id = ?',
      [title, description, valueChf, status, id]
    );

    res.status(200).json({ message: 'Help request updated successfully' });
  } catch (error) {
    console.error('Error updating help request:', error);
    res.status(500).json({ error: 'Internal server error', details: error.message });
  }
});

// DELETE /help-requests/:id - Delete a help request
router.delete('/:id', requireAuth, async (req, res) => {
  try {
    const { id } = req.params;
    
    // Check if the help request exists and belongs to the user
    const [existing] = await pool.query(
      'SELECT id FROM help_requests WHERE id = ? AND requester_id = ?',
      [id, req.user.userId]
    );

    if (existing.length === 0) {
      return res.status(404).json({ error: 'Help request not found or unauthorized' });
    }

    const [result] = await pool.query(
      'DELETE FROM help_requests WHERE id = ?',
      [id]
    );

    res.status(200).json({ message: 'Help request deleted successfully' });
  } catch (error) {
    console.error('Error deleting help request:', error);
    res.status(500).json({ error: 'Internal server error', details: error.message });
  }
});

export default router;