import { NextRequest, NextResponse } from "next/server";
import { execute } from "@/lib/db";
import { getSession } from "@/lib/session";
import { createObjectId } from "@/lib/utils";
import { getStdCategoryByAlias, validateStdCodeId } from "@/lib/procurement-std";

// 구매품표준코드 저장 (procurStandMgmt.saveCODE1Info 대응)
// body: { actionType, objId?, code_group(alias), code_id, code_name, detail?, status? }
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 alias = String(body.code_group || "");
  const def = getStdCategoryByAlias(alias);
  if (!def) {
    return NextResponse.json({ success: false, message: "카테고리가 올바르지 않습니다." }, { status: 400 });
  }

  const codeId = String(body.code_id || "").toUpperCase();
  const codeName = String(body.code_name || "").trim();

  if (!codeName) {
    return NextResponse.json({ success: false, message: "구분을 입력하세요." }, { status: 400 });
  }
  const v = validateStdCodeId(alias, codeId);
  if (!v.ok) {
    return NextResponse.json({ success: false, message: v.message }, { status: 400 });
  }

  const isNew = !body.objId || body.actionType === "regist";
  const objId = isNew ? createObjectId() : String(body.objId);
  const detail = def.showDetail ? (body.detail || "") : "";
  const status = body.status || "active";

  try {
    await execute(
      `INSERT INTO procurement_standard (objid, code_name, code_id, detail, category, regdate, writer, status)
       VALUES ($1, $2, $3, $4, $5, NOW(), $6, $7)
       ON CONFLICT (objid) DO UPDATE SET
         code_name = EXCLUDED.code_name,
         code_id = EXCLUDED.code_id,
         detail = EXCLUDED.detail,
         category = EXCLUDED.category,
         status = EXCLUDED.status,
         editdate = NOW(),
         edit_user = EXCLUDED.writer`,
      [objId, codeName, codeId, detail, def.category, user.userId, status]
    );
    // 코드명 변경 시 part_mng 쪽 컬럼 동기화 (원본 updateCodeName 대응)
    // 해당 category에 소속된 code_id일 때만, part_mng.MAJOR_CATEGORY 등 컬럼 업데이트
    const colMap: Record<string, string> = {
      CODE1: "major_category",
      CODE2: "sub_category",
      CODE3: "maker",
      CODE4: "part_name",
      CODE5: "spec",
    };
    const partMngCol = colMap[alias];
    if (partMngCol) {
      await execute(
        `UPDATE part_mng SET ${partMngCol} = $1 WHERE ${alias.toLowerCase()} = $2`,
        [codeName, codeId]
      );
    }

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