// ============================================================
// 생산관리 > 생산계획&실적관리 (일반/장비) + 반제품·원자재 소요량.
// wace productionplanning.xml 1:1.
//
// 라우트:
//   GET  /api/production/plan-result/list             (메뉴1 — 일반)
//   GET  /api/production/plan-result/list-equip       (메뉴2 — 장비)
//   GET  /api/production/plan-result/project-options  (검색 multiple — 프로젝트번호)
//   GET  /api/production/plan-result/writer-options   (검색 — 등록자)
//
//   GET  /api/production/mbom-requirement/options     (M-BOM 옵션 + 품명 매핑)
//   POST /api/production/mbom-requirement/semi        (메뉴3 — 반제품)
//   POST /api/production/mbom-requirement/raw         (메뉴4 — 원자재)
// ============================================================

import { Response } from "express";
import { AuthenticatedRequest } from "../types/auth";
import * as ppr from "../services/prodPlanResultService";
import * as req from "../services/mbomRequirementService";
import { logger } from "../utils/logger";

function parseFilter(q: Record<string, any>): ppr.ProdPlanResultFilter {
  const f: ppr.ProdPlanResultFilter = { ...q };
  if (q.page) f.page = Number(q.page);
  if (q.page_size) f.page_size = Number(q.page_size);
  return f;
}

// ─── 메뉴 1: 생산계획&실적관리 (일반) ─────────────────────────

export async function getList(reqMsg: AuthenticatedRequest, res: Response) {
  try {
    const data = await ppr.listGeneral(parseFilter(reqMsg.query as Record<string, any>));
    return res.json({ success: true, data });
  } catch (e: any) {
    logger.error("생산계획&실적관리 목록 실패", { error: e.message });
    return res.status(500).json({ success: false, message: e.message });
  }
}

// ─── 메뉴 2: 생산계획&실적관리 (장비) ─────────────────────────

export async function getListEquip(reqMsg: AuthenticatedRequest, res: Response) {
  try {
    const data = await ppr.listEquip(parseFilter(reqMsg.query as Record<string, any>));
    return res.json({ success: true, data });
  } catch (e: any) {
    logger.error("생산계획&실적관리(장비) 목록 실패", { error: e.message });
    return res.status(500).json({ success: false, message: e.message });
  }
}

// ─── 검색 옵션 ────────────────────────────────────────────────

export async function getProjectOptions(_req: AuthenticatedRequest, res: Response) {
  try {
    const data = await ppr.getProjectNoOptions();
    return res.json({ success: true, data });
  } catch (e: any) {
    logger.error("프로젝트번호 옵션 실패", { error: e.message });
    return res.status(500).json({ success: false, message: e.message });
  }
}

export async function getWriterOptions(_req: AuthenticatedRequest, res: Response) {
  try {
    const data = await ppr.getWriterOptions();
    return res.json({ success: true, data });
  } catch (e: any) {
    logger.error("등록자 옵션 실패", { error: e.message });
    return res.status(500).json({ success: false, message: e.message });
  }
}

// ─── 메뉴 3 & 4: M-BOM 소요량 ─────────────────────────────────

export async function getMbomOptions(_req: AuthenticatedRequest, res: Response) {
  try {
    const data = await req.getMbomOptions();
    return res.json({ success: true, data });
  } catch (e: any) {
    logger.error("M-BOM 옵션 실패", { error: e.message });
    return res.status(500).json({ success: false, message: e.message });
  }
}

export async function getSemiRequirement(reqMsg: AuthenticatedRequest, res: Response) {
  try {
    const items = Array.isArray(reqMsg.body?.mbomItems) ? reqMsg.body.mbomItems : [];
    const data = await req.getSemiRequirement(items);
    return res.json({ success: true, data });
  } catch (e: any) {
    logger.error("반제품 소요량 조회 실패", { error: e.message });
    return res.status(500).json({ success: false, message: e.message });
  }
}

export async function getRawRequirement(reqMsg: AuthenticatedRequest, res: Response) {
  try {
    const items = Array.isArray(reqMsg.body?.mbomItems) ? reqMsg.body.mbomItems : [];
    const data = await req.getRawRequirement(items);
    return res.json({ success: true, data });
  } catch (e: any) {
    logger.error("원자재 소요량 조회 실패", { error: e.message });
    return res.status(500).json({ success: false, message: e.message });
  }
}
