// ============================================================
// 프로젝트관리 > 제품구분_WBS관리 controller
// projectMgmtController 패턴 따라 { success, data } envelope.
// ============================================================

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

// GET /api/project/wbs-template?product=...
export async function getList(req: AuthenticatedRequest, res: Response) {
  try {
    const data = await svc.listTemplates({
      product: (req.query.product as string) || undefined,
    });
    return res.json({ success: true, data });
  } catch (e: any) {
    logger.error("WBS 템플릿 목록 실패", { error: e.message });
    return res.status(500).json({ success: false, message: e.message });
  }
}

// GET /api/project/wbs-template/check-duplicate?product=...&title=...
export async function checkDuplicate(req: AuthenticatedRequest, res: Response) {
  try {
    const product = (req.query.product as string) || "";
    const title = (req.query.title as string) || "";
    if (!product || !title) {
      return res.json({ success: true, data: { duplicate: false } });
    }
    const duplicate = await svc.checkDuplicate(product, title);
    return res.json({ success: true, data: { duplicate } });
  } catch (e: any) {
    logger.error("WBS 템플릿 중복 체크 실패", { error: e.message });
    return res.status(500).json({ success: false, message: e.message });
  }
}

// GET /api/project/wbs-template/:id  (헤더 + 트리)
export async function getById(req: AuthenticatedRequest, res: Response) {
  try {
    const result = await svc.getById(req.params.id);
    if (!result.master) {
      return res.status(404).json({ success: false, message: "템플릿을 찾을 수 없습니다." });
    }
    return res.json({ success: true, data: result });
  } catch (e: any) {
    logger.error("WBS 템플릿 상세 실패", { error: e.message });
    return res.status(500).json({ success: false, message: e.message });
  }
}

// POST /api/project/wbs-template  (신규 + 수정 통합 — wace mergeExcelUploadWBS 1:1)
export async function save(req: AuthenticatedRequest, res: Response) {
  try {
    const userId = req.user?.userId || "";
    const data = await svc.saveTemplate(req.body, userId);
    return res.json({ success: true, message: "저장하였습니다.", data });
  } catch (e: any) {
    logger.error("WBS 템플릿 저장 실패", { error: e.message });
    return res.status(500).json({ success: false, message: e.message });
  }
}

// DELETE /api/project/wbs-template  (body { objids: string[] })
export async function remove(req: AuthenticatedRequest, res: Response) {
  try {
    const objids: string[] = Array.isArray(req.body?.objids) ? req.body.objids : [];
    const result = await svc.deleteTemplates(objids);
    return res.json({ success: true, ...result });
  } catch (e: any) {
    logger.error("WBS 템플릿 삭제 실패", { error: e.message });
    return res.status(500).json({ success: false, message: e.message });
  }
}

// POST /api/project/wbs-template/parse-excel  (multipart, field: file)
export async function parseExcel(req: AuthenticatedRequest, res: Response) {
  try {
    const file = (req as any).file as Express.Multer.File | undefined;
    if (!file) {
      return res.status(400).json({ success: false, message: "엑셀 파일이 필요합니다." });
    }
    const data = svc.parseExcel(file.buffer);
    return res.json({ success: true, data });
  } catch (e: any) {
    logger.error("WBS 엑셀 파싱 실패", { error: e.message });
    return res.status(500).json({ success: false, message: e.message });
  }
}
