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[] = ["1=1"];
  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);
  }

  // invoiceMgmtGridList 대응
  if (body.year) {
    conditions.push(`TO_CHAR(IM.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.invoice_date_from) {
    conditions.push(`IM.issuance_date >= $${idx++}`);
    params.push(body.invoice_date_from);
  }
  if (body.invoice_date_to) {
    conditions.push(`IM.issuance_date <= $${idx++}`);
    params.push(body.invoice_date_to);
  }

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

  const sql = `
    SELECT IM.objid::text AS "OBJID",
      IM.objid::text AS "INVOICE_NO",
      COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = POM.partner_objid LIMIT 1), '') AS "SUPPLIER_NAME",
      CM.contract_no AS "PROJECT_NO",
      IM.issuance_date AS "INVOICE_DATE",
      COALESCE(IM.price_sum::numeric, 0) AS "SUPPLY_AMOUNT",
      ROUND(COALESCE(IM.price_sum::numeric, 0) * 0.1) AS "TAX_AMOUNT",
      ROUND(COALESCE(IM.price_sum::numeric, 0) * 1.1) AS "TOTAL_AMOUNT",
      COALESCE((SELECT code_name FROM comm_code WHERE code_id = IM.status LIMIT 1), IM.status) AS "STATUS_NAME",
      COALESCE((SELECT user_name FROM user_info WHERE user_id = IM.writer LIMIT 1), '') AS "WRITER_NAME"
    FROM invoice_mgmt IM
    LEFT JOIN purchase_order_master POM ON POM.objid::text = IM.parent_objid
    LEFT JOIN contract_mgmt CM ON CM.objid = POM.contract_mgmt_objid
    WHERE ${where}
    ORDER BY IM.regdate DESC
  `;

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