import { NextRequest, NextResponse } from "next/server";
import { queryOne, queryRows } from "@/lib/db";
import { getSession } from "@/lib/session";
import { STD_CATEGORIES } from "@/lib/procurement-std";

// 팝업 로드: 코드 단건 + 자재코드 단건 + 자재 팝업용 드롭다운 옵션 5종
// body: { mode: "code"|"material"|"options", objId? }
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 mode = String(body.mode || "code");
  const objId = body.objId ? String(body.objId) : "";

  if (mode === "options") {
    // 자재코드 팝업에서 쓰는 5개 카테고리 옵션 목록
    const result: Record<string, { value: string; label: string; code_id: string; code_name: string }[]> = {};
    for (const def of Object.values(STD_CATEGORIES)) {
      const rows = await queryRows(
        `SELECT objid::text AS "OBJID", code_id AS "CODE_ID", code_name AS "CODE_NAME"
           FROM procurement_standard
          WHERE category = $1
            AND COALESCE(status, 'active') = 'active'
          ORDER BY code_id`,
        [def.category]
      );
      result[def.alias] = rows.map((r) => ({
        value: String(r.OBJID),
        label: `${r.CODE_ID} - ${r.CODE_NAME}`,
        code_id: String(r.CODE_ID),
        code_name: String(r.CODE_NAME),
      }));
    }
    return NextResponse.json({ success: true, data: result });
  }

  if (mode === "material") {
    if (!objId) return NextResponse.json({ success: true, data: null });
    const row = await queryOne(
      `SELECT T.objid::text AS "OBJID",
         T.part_no AS "PART_NO",
         T.major_category AS "MAJOR_CATEGORY",
         T.sub_category AS "SUB_CATEGORY",
         T.maker AS "MAKER",
         T.part_name AS "PART_NAME",
         T.spec AS "SPEC",
         T.code1 AS "CODE1",
         T.code2 AS "CODE2",
         T.code3 AS "CODE3",
         T.code4 AS "CODE4",
         T.code5 AS "CODE5",
         (SELECT objid::text FROM procurement_standard WHERE code_id = T.code1 AND category = '0001668' LIMIT 1) AS "CODE_OBJID1",
         (SELECT objid::text FROM procurement_standard WHERE code_id = T.code2 AND category = '0001669' LIMIT 1) AS "CODE_OBJID2",
         (SELECT objid::text FROM procurement_standard WHERE code_id = T.code3 AND category = '0001670' LIMIT 1) AS "CODE_OBJID3",
         (SELECT objid::text FROM procurement_standard WHERE code_id = T.code4 AND category = '0001671' LIMIT 1) AS "CODE_OBJID4",
         (SELECT objid::text FROM procurement_standard WHERE code_id = T.code5 AND category = '0001672' LIMIT 1) AS "CODE_OBJID5",
         T.status AS "STATUS"
       FROM part_mng T
       WHERE T.objid::text = $1`,
      [objId]
    );
    return NextResponse.json({ success: true, data: row || null });
  }

  // code mode
  if (!objId) return NextResponse.json({ success: true, data: null });
  const row = await queryOne(
    `SELECT objid::text AS "OBJID",
       code_id AS "CODE_ID",
       code_name AS "CODE_NAME",
       detail AS "DETAIL",
       category AS "CATEGORY",
       COALESCE(status, 'active') AS "STATUS"
     FROM procurement_standard
     WHERE objid::text = $1`,
    [objId]
  );
  return NextResponse.json({ success: true, data: row || null });
}
