import express from 'express';
import { DisputeService } from '../disputes/dispute-service.js';
import { DB } from '../db/index.js';

const router = express.Router();
const disputeService = new DisputeService(new DB());

// Create a new dispute
router.post('/', async (req, res) => {
  try {
    const { deal_id, opened_by_user_id, reason_code, summary, requested_outcome } = req.body;
    
    const dispute = await disputeService.createDispute({
      deal_id,
      opened_by_user_id,
      reason_code,
      summary,
      requested_outcome
    });
    
    res.status(201).json(dispute);
  } catch (error) {
    console.error('Error creating dispute:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// Get dispute by ID
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const dispute = await disputeService.getDisputeById(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: 'Internal server error' });
  }
});

// Update dispute status
router.post('/:id/status', async (req, res) => {
  try {
    const { id } = req.params;
    const { status, updated_by_user_id } = req.body;
    
    await disputeService.updateDisputeStatus(parseInt(id), status, updated_by_user_id);
    
    res.json({ message: 'Dispute status updated successfully' });
  } catch (error) {
    console.error('Error updating dispute status:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// Add evidence to a dispute
router.post('/:id/evidence', async (req, res) => {
  try {
    const { id } = req.params;
    const { user_id, evidence_data } = req.body;
    
    await disputeService.addEvidence(parseInt(id), user_id, evidence_data);
    
    res.json({ message: 'Evidence added successfully' });
  } catch (error) {
    console.error('Error adding evidence:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// Resolve a dispute
router.post('/:id/resolve', async (req, res) => {
  try {
    const { id } = req.params;
    const { resolved_by_user_id, decision, reason } = req.body;
    
    await disputeService.resolveDispute(parseInt(id), resolved_by_user_id, decision, reason);
    
    res.json({ message: 'Dispute resolved successfully' });
  } catch (error) {
    console.error('Error resolving dispute:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

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

export default router;