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[] = ["CM.contract_result = '0000964'"];
  const params: unknown[] = [];
  let idx = 1;

  if (body.year) {
    conditions.push(`TO_CHAR(TO_DATE(CM.contract_date, 'YYYY-MM-DD'), 'YYYY') = $${idx++}`);
    params.push(body.year);
  }
  if (body.project_no) {
    conditions.push(`CM.contract_no LIKE '%' || $${idx++} || '%'`);
    params.push(body.project_no);
  }

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

  const rows = await queryRows(
    `SELECT CM.objid::text AS "OBJID",
       CM.contract_no AS "PROJECT_NO",
       COALESCE((SELECT code_name FROM comm_code WHERE code_id = CM.product LIMIT 1), '') AS "PRODUCT_NAME",
       CM.project_name AS "UNIT_NAME",
       CM.facility_qty AS "PROD_QTY",
       0 AS "COMPLETE_QTY",
       0 AS "PROGRESS_RATE",
       CM.contract_del_date AS "START_DATE",
       CM.req_del_date AS "END_DATE",
       COALESCE((SELECT code_name FROM comm_code WHERE code_id = CM.contract_result LIMIT 1), '') AS "STATUS_NAME"
     FROM contract_mgmt CM
     WHERE ${where}
     ORDER BY CM.regdate DESC
`,
    params
  );

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