import { Request, Response } from 'express';
import { prisma } from '../models';
import { gradeBand, isJvAutoSwitch, isPremium, isWaste } from '../lib/module-b';
import { detectDilution } from '../lib/module-b/dilution';

export const gradeControlController = {
  async validateTruck(req: Request, res: Response) {
    const b = req.body as { ppm?: number; tons?: number; pit_id?: string };
    if (b.ppm == null || b.tons == null) {
      res.status(400).json({ success: false, error: 'ppm and tons required' });
      return;
    }
    const band = gradeBand(b.ppm);
    const accept = !isWaste(b.ppm);
    res.json({
      success: true,
      data: {
        accept,
        band,
        premium: isPremium(b.ppm),
        jv_band: isJvAutoSwitch(b.ppm),
        waste: isWaste(b.ppm),
        message: accept ? 'Load within processable grade' : 'Reject — waste band',
      },
    });
  },

  async wasteCall(req: Request, res: Response) {
    const b = req.body as { pit_id?: string; license_id?: string; ppm?: number; tons?: number };
    if (!b.pit_id || !b.license_id || b.ppm == null) {
      res.status(400).json({ success: false, error: 'pit_id, license_id, ppm required' });
      return;
    }
    if (!isWaste(b.ppm)) {
      res.status(400).json({ success: false, error: 'PPM is not in waste band' });
      return;
    }
    await prisma.gradeLoadLog.create({
      data: {
        pit_id: b.pit_id,
        license_id: b.license_id,
        ppm: b.ppm,
        tons: b.tons ?? 0,
        notes: 'WASTE_CALL',
      },
    });
    res.json({ success: true, data: { action: 'REQUEST_TRUCK', reason: 'waste' } });
  },

  async jvAutoSwitch(req: Request, res: Response) {
    const b = req.body as {
      pit_id?: string;
      license_id?: string;
      ppm?: number;
      tons?: number;
      original_owner?: string;
      triggered_by?: string;
    };
    if (!b.pit_id || !b.license_id || b.ppm == null || b.tons == null) {
      res.status(400).json({ success: false, error: 'pit_id, license_id, ppm, tons required' });
      return;
    }
    if (!isJvAutoSwitch(b.ppm)) {
      res.status(400).json({ success: false, error: 'PPM not in JV auto band (0.5–1.29)' });
      return;
    }
    const goldVal = b.tons * b.ppm * Number(process.env.MODULE_B_GOLD_VALUE_PER_PPM_TON ?? '50000');
    const log = await prisma.jVAutoSwitchLog.create({
      data: {
        pit_id: b.pit_id,
        license_id: b.license_id,
        original_ppm: b.ppm,
        original_owner: b.original_owner ?? 'WMCL',
        new_owner: 'JV_PARTNER',
        switch_reason: b.ppm < 1.29 ? 'BELOW_1.29_PPM' : 'JV_AGREEMENT',
        tons_affected: b.tons,
        gold_value_affected: goldVal,
        triggered_by: b.triggered_by ?? 'system',
      },
    });
    res.json({
      success: true,
      data: { log, notify_jv_partner: true },
    });
  },

  async dilutionAlert(req: Request, res: Response) {
    const pitId = String(req.params.pitId);
    const logs = await prisma.gradeLoadLog.findMany({
      where: { pit_id: pitId },
      orderBy: { created_at: 'desc' },
      take: 6,
    });
    if (logs.length < 2) {
      res.json({ success: true, data: { alert: false, reason: 'insufficient_history' } });
      return;
    }
    const latest = logs[0];
    const prior = logs.slice(1, 6);
    const flag = detectDilution(
      prior.map((l) => ({ ppm: l.ppm })),
      latest.ppm
    );
    if (flag) {
      const pit = await prisma.pit.findUnique({ where: { id: pitId } });
      const msg = `DILUTION ALERT: Possible ore mixing at Pit ${pit?.pit_name ?? pitId}`;
      await prisma.dilutionAlert.create({
        data: {
          pit_id: pitId,
          license_id: pit?.license_id ?? logs[0].license_id,
          message: msg,
          active: true,
        },
      });
      res.json({ success: true, data: { alert: true, message: msg, quarantine: true } });
      return;
    }
    res.json({ success: true, data: { alert: false } });
  },

  async dilutionList(req: Request, res: Response) {
    const alerts = await prisma.dilutionAlert.findMany({
      where: { active: true },
      orderBy: { created_at: 'desc' },
      take: 100,
    });
    res.json({ success: true, data: { alerts } });
  },

  async jvSwitchHistory(req: Request, res: Response) {
    const license_id = req.query.license_id as string | undefined;
    const logs = await prisma.jVAutoSwitchLog.findMany({
      where: license_id ? { license_id } : {},
      orderBy: { created_at: 'desc' },
      take: 200,
    });
    res.json({ success: true, data: { logs } });
  },
};
