import { NextRequest, NextResponse } from "next/server";
import { execute, queryOne } from "@/lib/db";
import { getSession } from "@/lib/session";
import { createObjectId } from "@/lib/utils";

// 자재코드 저장 (procurStandMgmt.mergeMaterialCode 대응)
// body: { actionType, objId?, code_objid1..5 } — procurement_standard.objid 5개
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json();
  const isNew = !body.objId || body.actionType === "regist";
  const objId = isNew ? createObjectId() : String(body.objId);

  const codeObjIds: string[] = [
    String(body.code_objid1 || ""),
    String(body.code_objid2 || ""),
    String(body.code_objid3 || ""),
    String(body.code_objid4 || ""),
    String(body.code_objid5 || ""),
  ];

  if (codeObjIds.some((v) => !v)) {
    return NextResponse.json({ success: false, message: "대분류/중분류/Maker/품명/규격을 모두 선택하세요." }, { status: 400 });
  }

  try {
    // 5개 카테고리 각각의 code_id, code_name 조회
    const categories = ["0001668", "0001669", "0001670", "0001671", "0001672"];
    const codes: { code_id: string; code_name: string }[] = [];
    for (let i = 0; i < 5; i++) {
      const row = await queryOne(
        `SELECT code_id AS "CODE_ID", code_name AS "CODE_NAME"
           FROM procurement_standard
          WHERE objid::text = $1 AND category = $2`,
        [codeObjIds[i], categories[i]]
      );
      if (!row) {
        return NextResponse.json({ success: false, message: `${["대분류","중분류","Maker","품명","규격"][i]} 선택값이 올바르지 않습니다.` }, { status: 400 });
      }
      codes.push({ code_id: String(row.CODE_ID), code_name: String(row.CODE_NAME) });
    }
    const materialCode = codes.map((c) => c.code_id).join("");

    // 중복 체크
    const dup = await queryOne(
      `SELECT objid::text AS "OBJID" FROM part_mng
        WHERE objid::text != $1
          AND REPLACE(TRIM(UPPER(part_no)), ' ', '') = REPLACE(TRIM(UPPER($2)), ' ', '')`,
      [objId, materialCode]
    );
    if (dup) {
      return NextResponse.json({ success: false, message: "중복되는 자재코드가 존재합니다." }, { status: 400 });
    }

    // EO_NO 생성 (원본: 'EOB' + yy + '-' + 4자리 순번, 신규만)
    let eoNo: string | null = null;
    if (isNew) {
      const row = await queryOne<{ EO_NO: string }>(
        `SELECT 'EOB' || TO_CHAR(NOW(), 'YY') || '-' ||
                LPAD(
                  (SELECT COALESCE(MAX(SUBSTR(eo_no, 7, 8)::INTEGER) + 1, 1)::TEXT
                     FROM part_mng
                    WHERE eo_no LIKE 'EOB%'), 4, '0'
                ) AS "EO_NO"`,
        []
      );
      eoNo = row ? String(row.EO_NO) : null;
    }

    if (isNew) {
      await execute(
        `INSERT INTO part_mng (
           objid, part_no, part_name, spec, major_category, sub_category, maker,
           code1, code2, code3, code4, code5,
           part_type, revision, status, reg_date, writer, is_last, is_new, is_longd, eo_no, design_date
         ) VALUES (
           $1::numeric, $2, $3, $4, $5, $6, $7,
           $8, $9, $10, $11, $12,
           '0001788', 'RE', 'release', NOW(), $13, '1', '1', '1', $14, TO_CHAR(NOW(), 'YYYY-MM-DD')
         )`,
        [
          objId, materialCode, codes[3].code_name, codes[4].code_name,
          codes[0].code_name, codes[1].code_name, codes[2].code_name,
          codes[0].code_id, codes[1].code_id, codes[2].code_id, codes[3].code_id, codes[4].code_id,
          user.userId, eoNo,
        ]
      );
    } else {
      await execute(
        `UPDATE part_mng SET
           part_no = $2,
           part_name = $3,
           spec = $4,
           major_category = $5,
           sub_category = $6,
           maker = $7,
           code1 = $8, code2 = $9, code3 = $10, code4 = $11, code5 = $12,
           edit_date = NOW(),
           writer = $13
         WHERE objid::text = $1`,
        [
          objId, materialCode, codes[3].code_name, codes[4].code_name,
          codes[0].code_name, codes[1].code_name, codes[2].code_name,
          codes[0].code_id, codes[1].code_id, codes[2].code_id, codes[3].code_id, codes[4].code_id,
          user.userId,
        ]
      );
    }

    return NextResponse.json({ success: true, objId, materialCode, message: isNew ? "등록되었습니다." : "수정되었습니다." });
  } catch (error) {
    console.error("Material code save:", error);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  }
}
