const express = require('express');
const router = express.Router();
const shipmentService = require('../services/shipmentService');

/**
 * GET /api/shipments/at-risk
 * Get all in-transit shipments with risk scores
 *
 * Query params:
 *   - warehouseId: filter by warehouse
 *   - region: filter by region
 *   - minRisk: minimum risk score (0-100)
 */
router.get('/shipments/at-risk', async (req, res) => {
  try {
    const { warehouseId, region, minRisk } = req.query;

    const shipments = await shipmentService.getAtRiskShipments({
      warehouseId: warehouseId ? parseInt(warehouseId) : null,
      region: region || null,
      minRiskScore: minRisk ? parseInt(minRisk) : 0
    });

    res.json({
      success: true,
      count: shipments.length,
      data: shipments
    });
  } catch (error) {
    console.error('Error fetching at-risk shipments:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to fetch shipments'
    });
  }
});

/**
 * GET /api/shipments/:id
 * Get detailed info for a single shipment
 */
router.get('/shipments/:id', async (req, res) => {
  try {
    const shipment = await shipmentService.getShipmentDetails(req.params.id);

    if (!shipment) {
      return res.status(404).json({
        success: false,
        error: 'Shipment not found'
      });
    }

    res.json({
      success: true,
      data: shipment
    });
  } catch (error) {
    console.error('Error fetching shipment:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to fetch shipment'
    });
  }
});

/**
 * GET /api/dashboard/stats
 * Get summary statistics for the dashboard
 */
router.get('/dashboard/stats', async (req, res) => {
  try {
    const stats = await shipmentService.getDashboardStats();

    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    console.error('Error fetching stats:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to fetch dashboard stats'
    });
  }
});

/**
 * GET /api/warehouses
 * Get list of warehouses for filter dropdown
 */
router.get('/warehouses', async (req, res) => {
  try {
    const warehouses = await shipmentService.getWarehouses();

    res.json({
      success: true,
      data: warehouses
    });
  } catch (error) {
    console.error('Error fetching warehouses:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to fetch warehouses'
    });
  }
});

/**
 * GET /api/regions
 * Get list of regions for filter dropdown
 */
router.get('/regions', async (req, res) => {
  try {
    const regions = await shipmentService.getRegions();

    res.json({
      success: true,
      data: regions.map(r => r.region)
    });
  } catch (error) {
    console.error('Error fetching regions:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to fetch regions'
    });
  }
});

module.exports = router;
