import { Router, Request, Response } from "express";
import path from "path";
import fs from "fs";

const router = Router();

const SCHEDULE_FILES: Record<string, string> = {
  MH: "procedureCodesMH.json",
  MASSHEALTH: "procedureCodesMH.json",
  CCA: "procedureCodesCCA.json",
  DDMA: "procedureCodesDDMA.json",
  TUFTSSCO: "procedureCodesTuftsSCO.json",
  TUFTS_SCO: "procedureCodesTuftsSCO.json",
  UNITEDDH: "procedureCodesUnitedDH.json",
  UNITED_SCO: "procedureCodesUnitedDH.json",
  UNITEDSCO: "procedureCodesUnitedDH.json",
};

function getSchedulePath(siteKey: string): string | null {
  const filename = SCHEDULE_FILES[siteKey.toUpperCase()];
  if (!filename) return null;
  return path.join(process.cwd(), "..", "Frontend", "src", "assets", "data", filename);
}

/**
 * POST /api/fee-schedule/update-price
 * Body: { siteKey, procedureCode, price }
 * Updates the matching row's Price field in the fee schedule JSON.
 */
router.post("/update-price", async (req: Request, res: Response): Promise<any> => {
  if (!req.user?.id) return res.status(401).json({ error: "Unauthorized" });

  const { siteKey, procedureCode, price } = req.body;
  if (!siteKey || !procedureCode || price == null) {
    return res.status(400).json({ error: "siteKey, procedureCode and price are required" });
  }

  const filePath = getSchedulePath(siteKey);
  if (!filePath) {
    return res.status(400).json({ error: `No fee schedule for siteKey: ${siteKey}` });
  }

  try {
    const raw = fs.readFileSync(filePath, "utf-8");
    const rows: any[] = JSON.parse(raw);
    const normalizedCode = String(procedureCode).trim().toUpperCase();
    let updated = false;

    for (const row of rows) {
      const rowCode = String(row["Procedure Code"] || "").trim().toUpperCase();
      if (rowCode === normalizedCode) {
        // Update whichever price field(s) exist in this row
        if ("Price" in row) row["Price"] = price;
        if ("PriceLTEQ21" in row) row["PriceLTEQ21"] = price;
        if ("PriceGT21" in row) row["PriceGT21"] = price;
        updated = true;
        break;
      }
    }

    if (!updated) {
      return res.status(404).json({ error: `Procedure code ${procedureCode} not found in ${siteKey} schedule` });
    }

    fs.writeFileSync(filePath, JSON.stringify(rows, null, 2), "utf-8");
    console.log(`[feeSchedule] Updated ${siteKey} ${procedureCode} → ${price}`);
    return res.json({ success: true });
  } catch (err: any) {
    console.error("[feeSchedule] Error:", err);
    return res.status(500).json({ error: err.message });
  }
});

export default router;
