import { Router, Response } from 'express';
import { requireAuth, AuthRequest } from '../../middleware/auth.middleware';
import { ProductionService } from '../../services/production.service';

const router = Router();
router.use(requireAuth);

// ─── Production chain definitions ────────────────────────────

/** GET /production/chains — List all production chains and cost ratios */
router.get('/chains', async (_req: AuthRequest, res: Response) => {
  try {
    const chains = ProductionService.getChains();
    const ratios = ProductionService.getCostRatios();
    res.json({ chains, ratios });
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

// ─── Player batches ──────────────────────────────────────────

/** GET /production/batches — Active production batches for current player */
router.get('/batches', async (req: AuthRequest, res: Response) => {
  try {
    const batches = await ProductionService.getPlayerBatches(req.playerId!);
    res.json(batches);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/** POST /production/start — Start a production batch */
router.post('/start', async (req: AuthRequest, res: Response) => {
  try {
    const { business_id, chain_type, product_name, quantity_kg } = req.body;

    if (!business_id || !chain_type || !product_name || !quantity_kg) {
      res.status(400).json({ error: 'business_id, chain_type, product_name et quantity_kg requis' });
      return;
    }

    const batch = await ProductionService.startBatch(req.playerId!, {
      business_id,
      chain_type,
      product_name,
      quantity_kg: Number(quantity_kg),
    });

    res.status(201).json(batch);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

/** POST /production/:batchId/collect — Collect a completed production batch */
router.post('/:batchId/collect', async (req: AuthRequest, res: Response) => {
  try {
    const result = await ProductionService.collectBatch(req.playerId!, req.params.batchId);
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

export default router;
