/**
 * 제일그라스 수주 엑셀 일괄 업로드 컨트롤러
 */
import { Request, Response } from "express";
import logger from "../utils/logger";
import { excelBulkUpload } from "../services/salesOrderBulkService";

export async function bulkUploadHandler(req: Request, res: Response): Promise<void> {
  try {
    const user = (req as any).user || {};
    const companyCode = user.companyCode;
    const userId = user.userId || user.username || "system";

    if (!companyCode) {
      res.status(401).json({ success: false, message: "로그인 정보 없음" });
      return;
    }

    const { rows, autoCreateItems, defaultItemDivision } = req.body || {};
    if (!Array.isArray(rows) || rows.length === 0) {
      res.status(400).json({ success: false, message: "업로드할 데이터가 없습니다." });
      return;
    }

    const result = await excelBulkUpload({
      companyCode,
      userId,
      rows,
      autoCreateItems,
      defaultItemDivision,
    });

    res.status(200).json({
      success: true,
      message: "업로드 완료",
      data: result,
    });
  } catch (err: any) {
    logger.error("수주 일괄 업로드 실패:", err);
    res.status(500).json({
      success: false,
      message: err?.message || "업로드 실패",
    });
  }
}
