import express from 'express';
import { DisputeFlowService } from './dispute-flow.service';

const router = express.Router();

// Create a new dispute
router.post('/disputes', async (req, res) => {
  try {
    const dispute = await DisputeFlowService.createDispute(req.body);
    res.status(201).json(dispute);
  } catch (error) {
    console.error('Error creating dispute:', error);
    res.status(500).json({ error: 'Failed to create dispute' });
  }
});

// Add evidence to a dispute
router.post('/disputes/:id/evidence', async (req, res) => {
  try {
    const { id } = req.params;
    const { actorUserId, ...evidenceData } = req.body;
    
    await DisputeFlowService.addEvidence(parseInt(id), actorUserId, evidenceData);
    res.status(200).json({ message: 'Evidence added successfully' });
  } catch (error) {
    console.error('Error adding evidence:', error);
    res.status(500).json({ error: 'Failed to add evidence' });
  }
});

// Update dispute status
router.post('/disputes/:id/status', async (req, res) => {
  try {
    const { id } = req.params;
    const { actorUserId, newStatus } = req.body;
    
    await DisputeFlowService.updateDisputeStatus(parseInt(id), actorUserId, newStatus);
    res.status(200).json({ message: 'Status updated successfully' });
  } catch (error) {
    console.error('Error updating dispute status:', error);
    res.status(500).json({ error: 'Failed to update status' });
  }
});

// Resolve a dispute
router.post('/disputes/:id/resolve', async (req, res) => {
  try {
    const { id } = req.params;
    const { actorUserId, ...decisionData } = req.body;
    
    await DisputeFlowService.resolveDispute(parseInt(id), actorUserId, decisionData);
    res.status(200).json({ message: 'Dispute resolved successfully' });
  } catch (error) {
    console.error('Error resolving dispute:', error);
    res.status(500).json({ error: 'Failed to resolve dispute' });
  }
});

// Get dispute details
router.get('/disputes/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const dispute = await DisputeFlowService.getDispute(parseInt(id));
    
    if (!dispute) {
      return res.status(404).json({ error: 'Dispute not found' });
    }
    
    res.json(dispute);
  } catch (error) {
    console.error('Error fetching dispute:', error);
    res.status(500).json({ error: 'Failed to fetch dispute' });
  }
});

// Get dispute events
router.get('/disputes/:id/events', async (req, res) => {
  try {
    const { id } = req.params;
    const events = await DisputeFlowService.getDisputeEvents(parseInt(id));
    res.json(events);
  } catch (error) {
    console.error('Error fetching dispute events:', error);
    res.status(500).json({ error: 'Failed to fetch dispute events' });
  }
});

export default router;