import { NextRequest, NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { getSession } from "@/lib/session";

// 제품관리_PART 및 구조등록 (structureList.jsp) 및 단순 BOM 조회 공용
// - mode: "structure" → PART_BOM_REPORT 구조 리스트 (getBOMStandardStructureGridList 대응)
// - 기본 → bom_part_qty 기반 단순 리스트
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 || "structure");

  if (mode === "structure" || mode === "register") {
    // getBOMStandardStructureGridList 대응
    const conditions: string[] = ["1=1"];
    const params: unknown[] = [];
    let idx = 1;

    if (body.customer_cd) {
      conditions.push(`T.customer_objid = $${idx++}`);
      params.push(body.customer_cd);
    }
    if (body.project_name) {
      conditions.push(`T.contract_objid = $${idx++}`);
      params.push(body.project_name);
    }
    if (body.unit_code) {
      conditions.push(`T.unit_code = $${idx++}`);
      params.push(body.unit_code);
    }
    if (body.SEARCH_UNIT_NAME) {
      conditions.push(`EXISTS (SELECT 'E' FROM pms_wbs_task W WHERE W.objid = T.unit_code
        AND (W.task_name LIKE UPPER('%'||$${idx}||'%') OR W.unit_no LIKE UPPER('%'||$${idx}||'%')))`);
      params.push(body.SEARCH_UNIT_NAME);
      idx++;
    }
    if (body.SEARCH_WRITER) {
      conditions.push(`T.writer = $${idx++}`);
      params.push(body.SEARCH_WRITER);
    }
    if (body.SEARCH_DEPLOY_DATE_FROM) {
      conditions.push(`T.deploy_date IS NOT NULL AND TO_DATE(T.deploy_date,'YYYY-MM-DD') >= $${idx++}::timestamp`);
      params.push(body.SEARCH_DEPLOY_DATE_FROM);
    }
    if (body.SEARCH_DEPLOY_DATE_TO) {
      conditions.push(`T.deploy_date IS NOT NULL AND TO_DATE(T.deploy_date,'YYYY-MM-DD') <= $${idx++}::timestamp`);
      params.push(body.SEARCH_DEPLOY_DATE_TO);
    }
    if (body.status) {
      conditions.push(`T.status = $${idx++}`);
      params.push(body.status);
    }

    const where = conditions.join(" AND ");

    const sql = `
      SELECT ROW_NUMBER() OVER(ORDER BY T.regdate DESC) AS "NUM",
        T.objid::text AS "OBJID",
        T.customer_objid AS "CUSTOMER_OBJID",
        (SELECT supply_name FROM supply_mng O WHERE O.objid::varchar = T.customer_objid) AS "CUSTOMER_NAME",
        T.contract_objid AS "CONTRACT_OBJID",
        (SELECT customer_project_name FROM project_mgmt O WHERE O.objid = T.contract_objid) AS "CUSTOMER_PROJECT_NAME",
        (SELECT project_no FROM project_mgmt O WHERE O.objid = T.contract_objid) AS "PROJECT_NO",
        T.unit_code AS "UNIT_CODE",
        (SELECT O.unit_no || '-' || O.task_name FROM pms_wbs_task O WHERE O.objid = T.unit_code) AS "UNIT_NAME",
        T.status AS "STATUS",
        CASE UPPER(T.status)
          WHEN 'CREATE' THEN '등록중'
          WHEN 'CHANGEDESIGN' THEN '설계변경미배포'
          WHEN 'DEPLOY' THEN '배포완료'
          ELSE ''
        END AS "STATUS_TITLE",
        T.writer AS "WRITER",
        (SELECT dept_name FROM user_info WHERE user_id = T.writer) AS "DEPT_NAME",
        (SELECT user_name FROM user_info WHERE user_id = T.writer) AS "USER_NAME",
        COALESCE((SELECT dept_name FROM user_info WHERE user_id = T.writer), '') || '/' ||
        COALESCE((SELECT user_name FROM user_info WHERE user_id = T.writer), '') AS "DEPT_USER_NAME",
        TO_CHAR(T.regdate, 'YYYY-MM-DD') AS "REG_DATE",
        T.deploy_date AS "DEPLOY_DATE",
        T.revision AS "REVISION",
        (SELECT MAX(PM.eo_no) FROM bom_part_qty BP LEFT JOIN part_mng PM ON BP.part_no = PM.objid::varchar
          WHERE BP.bom_report_objid = T.objid) AS "EO_NO",
        (SELECT MAX(PM.eo_date) FROM bom_part_qty BP LEFT JOIN part_mng PM ON BP.part_no = PM.objid::varchar
          WHERE BP.bom_report_objid = T.objid) AS "EO_DATE",
        T.note AS "NOTE",
        T.multi_yn AS "MULTI_YN",
        T.multi_master_yn AS "MULTI_MASTER_YN",
        T.multi_break_yn AS "MULTI_BREAK_YN",
        T.multi_master_objid AS "MULTI_MASTER_OBJID",
        (SELECT COUNT(*) FROM bom_part_qty A WHERE A.bom_report_objid = T.objid) AS "BOM_CNT"
      FROM part_bom_report T
      WHERE ${where}
      ORDER BY T.regdate DESC
    `;
    const rows = await queryRows(sql, params);
    return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
  }

  // 단순 BOM 리스트 (기존 방식 유지)
  const conditions: string[] = ["1=1"];
  const params: unknown[] = [];
  let idx = 1;

  if (body.part_name) { conditions.push(`P.part_name LIKE '%' || $${idx++} || '%'`); params.push(body.part_name); }
  if (body.part_no) { conditions.push(`P.part_no LIKE '%' || $${idx++} || '%'`); params.push(body.part_no); }
  if (body.project_no) { conditions.push(`B.project_no LIKE '%' || $${idx++} || '%'`); params.push(body.project_no); }

  const where = conditions.join(" AND ");
  const rows = await queryRows(
    `SELECT B.objid AS "OBJID",
       P.objid::text AS "PART_OBJID",
       P.part_no AS "PART_NO", P.part_name AS "PART_NAME",
       P.spec AS "SPEC", P.material AS "MATERIAL", P.unit AS "UNIT",
       COALESCE(B.qty::text, '') AS "BOM_QTY",
       COALESCE(B.bom_level::text, '1') AS "BOM_LEVEL",
       P.maker AS "MAKER", P.remark AS "REMARK", P.revision AS "REVISION",
       COALESCE((SELECT code_name FROM comm_code WHERE code_id = P.part_type LIMIT 1), '') AS "PART_TYPE_TITLE"
     FROM bom_part_qty B
     JOIN part_mng P ON P.objid::text = B.part_no
     WHERE P.status = 'release' AND ${where}
     ORDER BY B.parent_part_no, P.part_no
`, params,
  );
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
