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();

  // arrival_plan의 error_qty > 0 인 건이 부적합 (invalidMgmtGridList 대응)
  const conditions: string[] = ["AP.error_qty IS NOT NULL", "AP.error_qty != ''", "AP.error_qty != '0'"];
  const params: unknown[] = [];
  let idx = 1;

  if (body.year) {
    conditions.push(`TO_CHAR(CM.regdate, 'YYYY') = $${idx++}`);
    params.push(body.year);
  }
  if (body.partner_objid) {
    conditions.push(`POM.partner_objid = $${idx++}`);
    params.push(body.partner_objid);
  }
  if (body.project_no) {
    conditions.push(`CM.contract_no LIKE '%' || $${idx++} || '%'`);
    params.push(body.project_no);
  }
  if (body.defect_type || body.error_reason) {
    conditions.push(`AP.error_reason = $${idx++}`);
    params.push(body.defect_type || body.error_reason);
  }

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

  const sql = `
    SELECT AP.objid::text AS "OBJID",
      POM.purchase_order_no AS "PURCHASE_ORDER_NO",
      CM.contract_no AS "PROJECT_NO",
      COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = CM.customer_objid LIMIT 1), '') AS "CUSTOMER_NAME",
      COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = POM.partner_objid LIMIT 1), '') AS "PARTNER_NAME",
      POP.part_no AS "PART_NO",
      POP.part_name AS "PART_NAME",
      COALESCE((SELECT code_name FROM comm_code WHERE code_id = AP.error_reason LIMIT 1), '') AS "DEFECT_TYPE_NAME",
      AP.error_qty AS "DEFECT_QTY",
      COALESCE((SELECT code_name FROM comm_code WHERE code_id = AP.attribution LIMIT 1), '') AS "ATTRIBUTION_NAME",
      AP.receipt_date AS "REG_DATE",
      COALESCE((SELECT user_name FROM user_info WHERE user_id = AP.receiver_id LIMIT 1), '') AS "REG_USER_NAME",
      AP.re_arrival_plan_date AS "RE_ARRIVAL_PLAN_DATE",
      CASE WHEN COALESCE(AP.assembly_status, '') != '' THEN '처리완료' ELSE '미처리' END AS "STATUS_NAME",
      AP.group_seq AS "GROUP_SEQ",
      AP.seq AS "SEQ"
    FROM arrival_plan AP
    JOIN purchase_order_part POP ON POP.objid::text = AP.order_part_objid
    JOIN purchase_order_master POM ON POM.objid = POP.purchase_order_master_objid
    LEFT JOIN contract_mgmt CM ON CM.objid = POM.contract_mgmt_objid
    WHERE ${where}
    ORDER BY AP.group_seq, AP.seq
  `;

  const rows = await queryRows(sql, params);
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
