/**
 * ECR(Engineering Change Request) 관리 컨트롤러
 *  - 자바 ECRController 의 엔드포인트와 1:1 매핑되는 REST API 로 구현
 */
import { Response } from "express";
import { AuthenticatedRequest } from "../types/auth";
import { EcrMngService } from "../services/ecrMngService";

export class EcrMngController {
  /** GET /api/ecr — 목록 (?year, productCode, requestCode, writer, statusCode, page, pageSize) */
  static async list(req: AuthenticatedRequest, res: Response) {
    try {
      const data = await EcrMngService.list({
        year: req.query.year as string,
        productCode: req.query.productCode as string,
        requestCode: req.query.requestCode as string,
        writer: req.query.writer as string,
        statusCode: req.query.statusCode as string,
        page: Number(req.query.page) || 1,
        pageSize: Number(req.query.pageSize) || 20,
      });
      return res.json({ success: true, ...data });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: "ECR 목록 조회 실패", error: e?.message });
    }
  }

  /** GET /api/ecr/:objId — 상세 */
  static async detail(req: AuthenticatedRequest, res: Response) {
    try {
      const row = await EcrMngService.detail(req.params.objId);
      if (!row) return res.status(404).json({ success: false, message: "해당 ECR 을 찾을 수 없습니다." });
      return res.json({ success: true, data: row });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: "ECR 상세 조회 실패", error: e?.message });
    }
  }

  /** POST /api/ecr — 등록/수정 (merge) */
  static async merge(req: AuthenticatedRequest, res: Response) {
    try {
      const writer = req.user?.userId;
      if (!writer) return res.status(401).json({ success: false, message: "로그인이 필요합니다." });
      const r = await EcrMngService.merge({
        objId: req.body.objId,
        product_objid: req.body.product_objid,
        part_objid: req.body.part_objid,
        request_codeArr: req.body.request_codeArr,
        title: req.body.title,
        before_contents: req.body.before_contents,
        after_contents: req.body.after_contents,
        writer,
      });
      return res.json({ success: true, data: r, message: "저장되었습니다." });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: "ECR 저장 실패", error: e?.message });
    }
  }

  /** POST /api/ecr/:objId/complete — 조치완료 */
  static async complete(req: AuthenticatedRequest, res: Response) {
    try {
      const writer = req.user?.userId;
      if (!writer) return res.status(401).json({ success: false, message: "로그인이 필요합니다." });
      const r = await EcrMngService.complete({
        objId: req.params.objId,
        after_contents: req.body.after_contents,
        writer,
      });
      return res.json({ success: true, data: r, message: "조치완료 처리되었습니다." });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: "ECR 조치완료 실패", error: e?.message });
    }
  }

  /** DELETE /api/ecr — 삭제 (body.objIds: string[] 또는 콤마구분) */
  static async remove(req: AuthenticatedRequest, res: Response) {
    try {
      const raw = req.body.objIds ?? req.body.ecrobjid ?? "";
      const ids: string[] = Array.isArray(raw) ? raw : String(raw).split(",").filter(Boolean);
      const r = await EcrMngService.deleteByIds(ids);
      return res.json({ success: true, ...r, message: "삭제되었습니다." });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: "ECR 삭제 실패", error: e?.message });
    }
  }

  /** GET /api/ecr/options/writers */
  static async writerOptions(_req: AuthenticatedRequest, res: Response) {
    try {
      const data = await EcrMngService.writerOptions();
      return res.json({ success: true, data });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: "작성자 옵션 조회 실패", error: e?.message });
    }
  }

  /** GET /api/ecr/options/products */
  static async productOptions(_req: AuthenticatedRequest, res: Response) {
    try {
      const data = await EcrMngService.productOptions();
      return res.json({ success: true, data });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: "제품 옵션 조회 실패", error: e?.message });
    }
  }

  /** GET /api/ecr/options/parts */
  static async partOptions(_req: AuthenticatedRequest, res: Response) {
    try {
      const data = await EcrMngService.partOptions();
      return res.json({ success: true, data });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: "부품 옵션 조회 실패", error: e?.message });
    }
  }

  /** GET /api/ecr/options/codes/:parentCodeId — 0000090(요청), 0000099(상태) 등 */
  static async commCodeOptions(req: AuthenticatedRequest, res: Response) {
    try {
      const data = await EcrMngService.commCodeOptions(req.params.parentCodeId);
      return res.json({ success: true, data });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: "공통코드 옵션 조회 실패", error: e?.message });
    }
  }
}
