import { Response } from "express";
import { AuthenticatedRequest } from "../types/auth";
import * as salesEstimateService from "../services/salesEstimateService";
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 salesEstimateService.getList(filter);
    return res.json({ success: true, data });
  } catch (error: any) {
    logger.error("견적 목록 조회 실패", { error: error.message });
    return res.status(500).json({ success: false, message: error.message });
  }
}

export async function getById(req: AuthenticatedRequest, res: Response) {
  try {
    const { id } = req.params;
    const data = await salesEstimateService.getById(id);
    if (!data) {
      return res.status(404).json({ success: false, message: "견적을 찾을 수 없습니다." });
    }
    return res.json({ success: true, data });
  } catch (error: any) {
    logger.error("견적 상세 조회 실패", { error: error.message });
    return res.status(500).json({ success: false, message: error.message });
  }
}

export async function generateNumber(req: AuthenticatedRequest, res: Response) {
  try {
    const estimateNo = await salesEstimateService.generateNumber();
    return res.json({ success: true, data: { estimateNo } });
  } catch (error: any) {
    logger.error("견적번호 생성 실패", { error: error.message });
    return res.status(500).json({ success: false, message: error.message });
  }
}

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

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

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

export async function sendMail(req: AuthenticatedRequest, res: Response) {
  try {
    const userId = req.user!.userId;
    const { contractObjid, toEmails, ccEmails, subject, contents, pdfBase64, useAddEstOnly } = req.body ?? {};
    if (!contractObjid || !toEmails || !subject) {
      return res.status(400).json({
        success: false,
        message: "필수값 누락 (contractObjid, toEmails, subject)",
      });
    }
    const result = await salesEstimateService.sendMail(userId, {
      contractObjid,
      toEmails,
      ccEmails,
      subject,
      contents: contents ?? "",
      pdfBase64,
      useAddEstOnly,
    });
    if (!result.success) {
      return res.status(500).json(result);
    }
    return res.json(result);
  } catch (error: any) {
    logger.error("견적 메일 발송 실패", { error: error.message });
    return res.status(500).json({ success: false, message: error.message });
  }
}

/** GET /api/sales/estimate/:contractObjid/mail-info — 메일 다이얼로그 자동 채움용 (제목/수신/참조) */
export async function getMailInfo(req: AuthenticatedRequest, res: Response) {
  try {
    const { id } = req.params;
    const info = await salesEstimateService.getContractInfoForMail(id);
    if (!info) {
      return res.status(404).json({ success: false, message: "계약 정보를 찾을 수 없습니다." });
    }
    return res.json({ success: true, data: info });
  } catch (error: any) {
    logger.error("메일 자동채움 정보 조회 실패", { error: error.message });
    return res.status(500).json({ success: false, message: error.message });
  }
}

/** GET /api/sales/estimate/customer/:customerObjid/managers — 고객사 담당자 리스트 */
export async function getMailManagers(req: AuthenticatedRequest, res: Response) {
  try {
    const { customerObjid } = req.params;
    const managers = await salesEstimateService.getCustomerManagerList(customerObjid);
    return res.json({ success: true, data: managers });
  } catch (error: any) {
    logger.error("고객사 담당자 조회 실패", { error: error.message });
    return res.status(500).json({ success: false, message: error.message });
  }
}

// ──────────────────────────────────────────────────────────────
// G5 견적작성 — estimate_template
// ──────────────────────────────────────────────────────────────

export async function saveTemplate1(req: AuthenticatedRequest, res: Response) {
  try {
    const userId = req.user!.userId;
    const data = await salesEstimateService.saveEstimateTemplate1(userId, req.body);
    return res.json({ success: true, data, message: "견적서가 저장되었습니다." });
  } catch (error: any) {
    logger.error("견적작성(일반) 저장 실패", { error: error.message });
    return res.status(500).json({ success: false, message: error.message });
  }
}

export async function saveTemplate2(req: AuthenticatedRequest, res: Response) {
  try {
    const userId = req.user!.userId;
    const data = await salesEstimateService.saveEstimateTemplate2(userId, req.body);
    return res.json({ success: true, data, message: "견적서가 저장되었습니다." });
  } catch (error: any) {
    logger.error("견적작성(장비) 저장 실패", { error: error.message });
    return res.status(500).json({ success: false, message: error.message });
  }
}

export async function getTemplate(req: AuthenticatedRequest, res: Response) {
  try {
    const { templateObjid } = req.params;
    const data = await salesEstimateService.getTemplateById(templateObjid);
    if (!data) return res.status(404).json({ success: false, message: "견적서를 찾을 수 없습니다." });
    return res.json({ success: true, data });
  } catch (error: any) {
    logger.error("견적작성 단건 조회 실패", { error: error.message });
    return res.status(500).json({ success: false, message: error.message });
  }
}

export async function listTemplates(req: AuthenticatedRequest, res: Response) {
  try {
    const { contractObjid } = req.params;
    const data = await salesEstimateService.listTemplatesByContract(contractObjid);
    return res.json({ success: true, data });
  } catch (error: any) {
    logger.error("견적 차수 리스트 조회 실패", { error: error.message });
    return res.status(500).json({ success: false, message: error.message });
  }
}

// G4/G11 동일 패턴 — 견적 결재상신 (Amaranth SSO URL 발급 + amaranth_approval 매핑)
// wace estimateList_new.jsp:887 fn_openAmaranthApproval + 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 salesEstimateService.startEstimateApproval(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 });
  }
}
