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

// 사양관리 목록 조회
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 conditions: string[] = ["1=1"];
  const params: unknown[] = [];
  let idx = 1;

  if (body.project_no) {
    conditions.push(`CM.contract_no LIKE '%' || $${idx++} || '%'`);
    params.push(body.project_no);
  }
  if (body.spec_name) {
    conditions.push(`PS.spec_name LIKE '%' || $${idx++} || '%'`);
    params.push(body.spec_name);
  }

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

  const rows = await queryRows(
    `SELECT PS.objid::text AS "OBJID",
       CM.contract_no AS "PROJECT_NO",
       CM.project_name AS "PROJECT_NAME",
       PS.spec_name AS "SPEC_NAME",
       PS.spec_value AS "SPEC_VALUE",
       PS.unit AS "UNIT",
       PS.remark AS "REMARK",
       TO_CHAR(PS.reg_date, 'YYYY-MM-DD') AS "REG_DATE",
       COALESCE((SELECT user_name FROM user_info WHERE user_id = PS.writer LIMIT 1), '') AS "REG_USER_NAME"
     FROM product_spec PS
     LEFT JOIN contract_mgmt CM ON CM.objid::text = PS.contract_objid
     WHERE ${where}
     ORDER BY PS.reg_date DESC
`,
    params
  );

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