/**
 * Wace PLM 결재(APPROVAL) 컨트롤러
 *  - wace_plm 의 ApprovalController 1:1 포팅 — target_objid 기반 결재 라이프사이클
 *  - 기존 backend-node/src/controllers/approvalController.ts (ApprovalDefinitionController) 와는 별개
 */
import { Response } from "express";
import { AuthenticatedRequest } from "../types/auth";
import { ApprovalService } from "../services/approvalService";

export class WacePlmApprovalController {
  /** GET /api/wace-approval/inbox */
  static async listInbox(req: AuthenticatedRequest, res: Response) {
    try {
      const data = await ApprovalService.listInbox({
        connectUserId: req.user?.userId,
        systemType: req.query.systemType as string,
        approvalTitle: req.query.approvalTitle as string,
        fromDate: req.query.fromDate as string,
        toDate: req.query.toDate as string,
        writerUserName: req.query.writerUserName as string,
        approvalStatus: req.query.approvalStatus as string,
        headerApprovalStatus: req.query.headerApprovalStatus as any,
        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: "결재함 조회 실패", error: e?.message });
    }
  }

  /** GET /api/wace-approval/:approvalObjid */
  static async detail(req: AuthenticatedRequest, res: Response) {
    try {
      const data = await ApprovalService.getDetail(req.params.approvalObjid);
      if (!data) return res.status(404).json({ success: false, message: "결재를 찾을 수 없습니다." });
      return res.json({ success: true, data });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: "결재 상세 조회 실패", error: e?.message });
    }
  }

  /** POST /api/wace-approval/start — { targetObjid, targetType, title, description, approvers:[{userId,type}] } */
  static async start(req: AuthenticatedRequest, res: Response) {
    try {
      const writer = req.user?.userId;
      if (!writer) return res.status(401).json({ success: false, message: "로그인이 필요합니다." });
      const data = await ApprovalService.startApproval({
        targetObjid: req.body.targetObjid,
        targetType: req.body.targetType,
        systemType: req.body.systemType,
        title: req.body.title,
        description: req.body.description,
        writer,
        approvers: req.body.approvers || [],
      });
      return res.json({ success: true, data, message: "상신되었습니다." });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: "결재 상신 실패", error: e?.message });
    }
  }

  /** POST /api/wace-approval/inbox/:objid/approve */
  static async approve(req: AuthenticatedRequest, res: Response) {
    try {
      const userId = req.user?.userId;
      if (!userId) return res.status(401).json({ success: false, message: "로그인이 필요합니다." });
      const data = await ApprovalService.approveTask({
        inboxtaskObjid: req.params.objid,
        userId,
        comment: req.body.comment,
      });
      return res.json({ success: true, data, message: data.completed ? "최종 결재 완료" : "다음 결재자 대기" });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: e?.message || "결재 승인 실패" });
    }
  }

  /** POST /api/wace-approval/inbox/:objid/reject */
  static async reject(req: AuthenticatedRequest, res: Response) {
    try {
      const userId = req.user?.userId;
      if (!userId) return res.status(401).json({ success: false, message: "로그인이 필요합니다." });
      const data = await ApprovalService.rejectTask({
        inboxtaskObjid: req.params.objid,
        userId,
        comment: req.body.comment,
      });
      return res.json({ success: true, data, message: "반려되었습니다." });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: e?.message || "결재 반려 실패" });
    }
  }

  /** POST /api/wace-approval/:approvalObjid/amaranth-link — Amaranth SSO 발급 */
  static async amaranthLink(req: AuthenticatedRequest, res: Response) {
    try {
      const writer = req.user?.userId;
      if (!writer) return res.status(401).json({ success: false, message: "로그인이 필요합니다." });
      const data = await ApprovalService.linkAmaranth({
        approvalObjid: req.params.approvalObjid,
        targetObjid: req.body.targetObjid,
        targetType: req.body.targetType,
        empSeq: req.body.empSeq,
        compSeq: req.body.compSeq,
        deptSeq: req.body.deptSeq,
        outProcessCode: req.body.outProcessCode,
        formId: req.body.formId,
        subjectStr: req.body.subjectStr,
        loginId: req.body.loginId || req.user?.userId,
        writer,
      });
      return res.json({ success: true, data });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: e?.message });
    }
  }

  /** GET /api/wace-approval/by-target?targetObjid=&targetType= — 특정 target 의 최신 결재 */
  static async byTarget(req: AuthenticatedRequest, res: Response) {
    try {
      const data = await ApprovalService.getLastApprovalByTarget(
        String(req.query.targetObjid || ""),
        req.query.targetType ? String(req.query.targetType) : undefined,
      );
      return res.json({ success: true, data });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: e?.message });
    }
  }
}
