import { Response } from "express";
import { AuthenticatedRequest } from "../types/auth";
import * as svc from "../services/salesOrderMgmtService";
import { logger } from "../utils/logger";

export async function getList(req: AuthenticatedRequest, res: Response) {
  try {
    const filter = req.query as Record<string, string>;
    const data = await svc.getList(filter);
    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 getById(req: AuthenticatedRequest, res: Response) {
  try {
    const { id } = req.params;
    const data = await svc.getById(id);
    if (!data) return res.status(404).json({ success: false, message: "주문서를 찾을 수 없습니다." });
    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 generateNumber(req: AuthenticatedRequest, res: Response) {
  try {
    const contractNo = await svc.generateContractNo();
    return res.json({ success: true, data: { contractNo } });
  } catch (e: any) { return res.status(500).json({ success: false, message: e.message }); }
}

export async function create(req: AuthenticatedRequest, res: Response) {
  try {
    const userId = req.user!.userId;
    const data = await svc.create(userId, req.body);
    return res.status(201).json({ success: true, data, message: "주문서가 등록되었습니다." });
  } catch (e: any) { logger.error("주문서 등록 실패", { error: e.message }); return res.status(500).json({ success: false, message: e.message }); }
}

export async function update(req: AuthenticatedRequest, res: Response) {
  try {
    const userId = req.user!.userId;
    const { id } = req.params;
    await svc.update(userId, id, req.body);
    return res.json({ success: true, message: "주문서가 수정되었습니다." });
  } catch (e: any) { logger.error("주문서 수정 실패", { error: e.message }); return res.status(500).json({ success: false, message: e.message }); }
}

export async function remove(req: AuthenticatedRequest, res: Response) {
  try {
    const { id } = req.params;
    await svc.remove(id);
    return res.json({ success: true, message: "주문서가 삭제되었습니다." });
  } catch (e: any) {
    logger.error("주문서 삭제 실패", { error: e.message });
    // AppError(statusCode) 우선 — G8 guard 409 등
    return res.status(e?.statusCode ?? 500).json({ success: false, message: e.message });
  }
}

export async function getFormView(req: AuthenticatedRequest, res: Response) {
  try {
    const { id } = req.params;
    const data = await svc.getOrderFormView(id);
    if (!data) return res.status(404).json({ success: false, message: "주문서를 찾을 수 없습니다." });
    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 updateStatus(req: AuthenticatedRequest, res: Response) {
  try {
    const userId = req.user!.userId;
    const { id } = req.params;
    const { contract_result } = req.body;
    await svc.updateStatus(userId, id, contract_result);
    return res.json({ success: true, message: "수주 상태가 변경되었습니다." });
  } catch (e: any) { logger.error("수주 상태 변경 실패", { error: e.message }); return res.status(500).json({ success: false, message: e.message }); }
}

// G4/G11 수주 결재상신 — Amaranth SSO URL 발급 + amaranth_approval 매핑
// wace orderMgmtList.btnApproval + ApprovalService.getAmaranthSsoUrl 1:1
export async function startApproval(req: AuthenticatedRequest, res: Response) {
  try {
    const userId = req.user!.userId;
    const { id } = req.params;
    const { approvalTitle, subjectStr } = req.body || {};
    const data = await svc.startOrderApproval(userId, id, { approvalTitle, subjectStr });
    return res.json({ success: true, data, message: "결재 SSO URL이 발급되었습니다." });
  } catch (e: any) {
    logger.error("수주 결재상신 실패", { error: e.message });
    return res.status(e?.statusCode ?? 500).json({ success: false, message: e.message });
  }
}

// G9 수주복사 (wace orderMgmtList btnCopy → copyEstimateAndOrderInfo 1:1)
export async function copyOrder(req: AuthenticatedRequest, res: Response) {
  try {
    const userId = req.user!.userId;
    const { id } = req.params;
    const data = await svc.copyOrder(userId, id);
    return res.status(201).json({ success: true, data, message: "수주가 복사되었습니다." });
  } catch (e: any) {
    logger.error("수주복사 실패", { error: e.message });
    return res.status(e?.statusCode ?? 500).json({ success: false, message: e.message });
  }
}

// 수주취소: 라인별 cancel_qty 다중 UPDATE (wace saveOrderCancelQty 이식)
export async function saveCancelQty(req: AuthenticatedRequest, res: Response) {
  try {
    const userId = req.user!.userId;
    const { entries } = req.body as { entries: svc.CancelQtyEntry[] };
    const result = await svc.saveOrderCancelQty(userId, entries);
    if (result.result === "false") return res.status(400).json({ success: false, message: result.msg });
    return res.json({ success: true, message: result.msg });
  } catch (e: any) { logger.error("수주취소 저장 실패", { error: e.message }); return res.status(500).json({ success: false, message: e.message }); }
}
