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

// 구매품표준관리 목록 조회 (procurStandMgmt.mainCategoryGridList / materialCodeGridList 대응)
// code_group = "CODE1"~"CODE5" → procurement_standard (카테고리별)
// code_group = "MATERIAL_CODE" → part_mng
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 codeGroup = String(body.code_group || "");

  // === 자재코드 모드 ===
  if (codeGroup === "MATERIAL_CODE") {
    const conditions: string[] = ["T.is_new = '1'"];
    const params: unknown[] = [];
    let idx = 1;

    if (body.part_no) {
      conditions.push(`UPPER(T.part_no) LIKE UPPER('%' || $${idx++} || '%')`);
      params.push(body.part_no);
    }
    if (body.large_cd) {
      conditions.push(`UPPER(T.major_category) LIKE UPPER('%' || $${idx++} || '%')`);
      params.push(body.large_cd);
    }
    if (body.middle_cd) {
      conditions.push(`UPPER(T.sub_category) LIKE UPPER('%' || $${idx++} || '%')`);
      params.push(body.middle_cd);
    }
    if (body.maker) {
      conditions.push(`UPPER(T.maker) LIKE UPPER('%' || $${idx++} || '%')`);
      params.push(body.maker);
    }
    if (body.part_name) {
      conditions.push(`UPPER(T.part_name) LIKE UPPER('%' || $${idx++} || '%')`);
      params.push(body.part_name);
    }
    if (body.spec) {
      conditions.push(`UPPER(T.spec) LIKE UPPER('%' || $${idx++} || '%')`);
      params.push(body.spec);
    }

    const rows = await queryRows(
      `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",
         T.revision AS "REVISION",
         T.eo_no AS "EO_NO",
         TO_CHAR(T.eo_date::date, 'YYYY-MM-DD') AS "EO_DATE"
       FROM part_mng T
       WHERE ${conditions.join(" AND ")}
       ORDER BY T.reg_date DESC
`,
      params
    );
    return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
  }

  // === 코드1~5 카테고리 모드 ===
  const def = getStdCategoryByAlias(codeGroup);
  const conditions: string[] = [];
  const params: unknown[] = [];
  let idx = 1;

  if (def) {
    conditions.push(`PS.category = $${idx++}`);
    params.push(def.category);
  }
  if (body.code_name) {
    conditions.push(`PS.code_name LIKE '%' || $${idx++} || '%'`);
    params.push(body.code_name);
  }
  if (body.code_id) {
    conditions.push(`PS.code_id LIKE '%' || $${idx++} || '%'`);
    params.push(body.code_id);
  }

  const where = conditions.length > 0 ? conditions.join(" AND ") : "1=1";

  const rows = await queryRows(
    `SELECT PS.objid::text AS "OBJID",
       PS.code_id AS "CODE_ID",
       PS.code_name AS "CODE_NAME",
       PS.detail AS "DETAIL",
       PS.category AS "CATEGORY",
       COALESCE(PS.status, 'active') AS "STATUS",
       COALESCE((SELECT user_name FROM user_info WHERE user_id = PS.writer LIMIT 1), PS.writer) AS "WRITER_NAME",
       TO_CHAR(PS.regdate, 'YYYY-MM-DD') AS "REG_DATE"
     FROM procurement_standard PS
     WHERE ${where}
     ORDER BY PS.code_id`,
    params
  );

  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}

// 구매품표준관리 삭제
export async function DELETE(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json();
  const { objIds, mode } = body;

  if (!objIds || !Array.isArray(objIds) || objIds.length === 0) {
    return NextResponse.json({ success: false, message: "삭제할 항목을 선택하세요." });
  }

  try {
    const placeholders = objIds.map((_: string, i: number) => `$${i + 1}`).join(",");
    if (mode === "material") {
      await execute(`DELETE FROM part_mng WHERE objid IN (${placeholders})`, objIds);
    } else {
      await execute(`DELETE FROM procurement_standard WHERE objid IN (${placeholders})`, objIds);
    }
    return NextResponse.json({ success: true, message: `${objIds.length}건이 삭제되었습니다.` });
  } catch (error) {
    console.error("Procurement std delete:", error);
    return NextResponse.json({ success: false, message: "삭제 중 오류가 발생했습니다." }, { status: 500 });
  }
}
