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

// SCM 부적합품관리 목록 조회
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[] = [];
  const params: unknown[] = [];
  let idx = 1;

  // SCM: filter by partner unless admin
  if (!user.isAdmin) {
    conditions.push(
      `POM.partner_objid = (SELECT objid::text FROM supply_mng WHERE UPPER(supply_code) = UPPER($${idx++}) LIMIT 1)`
    );
    params.push(user.partnerCd);
  }

  // invalidMgmtGridList 대응 — arrival_plan.error_qty 기반
  if (body.year) {
    conditions.push(`TO_CHAR(CM.regdate, 'YYYY') = $${idx++}`);
    params.push(body.year);
  }
  if (body.supplier_name) {
    conditions.push(`COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = POM.partner_objid LIMIT 1), '') LIKE '%' || $${idx++} || '%'`);
    params.push(body.supplier_name);
  }
  if (body.status_code) {
    conditions.push(`CASE WHEN COALESCE(AP.assembly_status, '') != '' THEN 'complete' ELSE 'pending' END = $${idx++}`);
    params.push(body.status_code);
  }

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

  const sql = `
    SELECT AP.objid::text AS "OBJID",
      POM.purchase_order_no AS "DEFECT_NO",
      CM.contract_no AS "PROJECT_NO",
      COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = POM.partner_objid LIMIT 1), '') AS "SUPPLIER_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.receipt_date AS "DEFECT_DATE",
      AP.error_qty AS "DEFECT_QTY",
      '' AS "ACTION_CONTENT",
      CASE WHEN COALESCE(AP.assembly_status, '') != '' THEN '처리완료' ELSE '미처리' END AS "STATUS_NAME"
    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 AP.error_qty IS NOT NULL AND AP.error_qty != '' AND AP.error_qty != '0' AND ${where}
    ORDER BY AP.receipt_date DESC
  `;

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