/**
 * Customer CS(고객 사후관리) 컨트롤러
 */
import { Response } from "express";
import { AuthenticatedRequest } from "../types/auth";
import { CustomerCsService } from "../services/customerCsService";

export class CustomerCsController {
  /** GET /api/customer-cs */
  static async list(req: AuthenticatedRequest, res: Response) {
    try {
      const data = await CustomerCsService.list({
        searchYear:         req.query.searchYear as string,
        mngType:            req.query.mngType as string,
        productDivision:    req.query.productDivision as string,
        customerName:       req.query.customerName as string,
        startReceptionDate: req.query.startReceptionDate as string,
        endReceptionDate:   req.query.endReceptionDate as string,
        eventLocation:      req.query.eventLocation as string,
        performer:          req.query.performer as string,
        startActionDate:    req.query.startActionDate as string,
        endActionDate:      req.query.endActionDate as string,
        measureType:        req.query.measureType as string,
        status:             req.query.status 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: "CS 목록 조회 실패", error: e?.message });
    }
  }

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

  /** POST /api/customer-cs */
  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 CustomerCsService.merge({ ...req.body, writer });
      return res.json({ success: true, data: r, message: "저장되었습니다." });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: "CS 저장 실패", error: e?.message });
    }
  }

  /** DELETE /api/customer-cs */
  static async remove(req: AuthenticatedRequest, res: Response) {
    try {
      const raw = req.body.objIds ?? "";
      const ids: string[] = Array.isArray(raw) ? raw : String(raw).split(",").filter(Boolean);
      const r = await CustomerCsService.deleteByIds(ids);
      return res.json({ success: true, ...r, message: "삭제되었습니다." });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: "CS 삭제 실패", error: e?.message });
    }
  }

  /** GET /api/customer-cs/dashboard?searchYear=YYYY */
  static async dashboard(req: AuthenticatedRequest, res: Response) {
    try {
      const data = await CustomerCsService.dashboard(req.query.searchYear as string);
      return res.json({ success: true, data });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: "CS 대시보드 조회 실패", error: e?.message });
    }
  }

  /** GET /api/customer-cs/options/categories — 카테고리 ID 매핑 */
  static categoriesOptions(_req: AuthenticatedRequest, res: Response) {
    return res.json({ success: true, data: CustomerCsService.categories() });
  }

  /** GET /api/customer-cs/options/codes/:parentCodeId */
  static async codeOptions(req: AuthenticatedRequest, res: Response) {
    try {
      const data = await CustomerCsService.commCodeOptions(req.params.parentCodeId);
      return res.json({ success: true, data });
    } catch (e: any) {
      return res.status(500).json({ success: false, message: "공통코드 옵션 조회 실패", error: e?.message });
    }
  }
}
