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

// momo_orders 에 편집 락 컬럼이 없으면 1회 자동 증설
let lockColsEnsured = false;
async function ensureLockCols() {
  if (lockColsEnsured) return;
  try {
    await pool.query(`
      ALTER TABLE momo_orders
        ADD COLUMN IF NOT EXISTS editing_by TEXT,
        ADD COLUMN IF NOT EXISTS editing_at TIMESTAMP;
    `);
    lockColsEnsured = true;
  } catch (err) {
    console.error("[orders/list/ensureLockCols]", err);
  }
}
import { requireMomoUser } from "@/lib/momo-guard";

export async function POST(req: NextRequest) {
  const r = await requireMomoUser();
  if (r instanceof NextResponse) return r;
  await ensureLockCols();

  const body = await req.json().catch(() => ({}));
  const { dateFrom, dateTo, status, statuses, customerObjid, keyword, mine } = body as {
    dateFrom?: string; dateTo?: string; status?: string; statuses?: string[];
    customerObjid?: string; keyword?: string;
    mine?: boolean;
  };

  const conditions: string[] = ["COALESCE(O.is_del,'N') != 'Y'"];
  const params: unknown[] = [];
  let i = 1;

  const isAdmin = r.user.isAdmin === true || r.user.role === "ADMIN" || r.user.userType === "A";
  // 사용자 측 '내 발주 이력' 페이지는 mine=true 로 호출 → admin 이라도 본인 발주만.
  // admin 메뉴 (출고관리/입금관리/계산서 등) 는 mine 안 보냄 → 전체 또는 customerObjid 필터.
  if (mine === true || !isAdmin) {
    const own = r.user.objid ?? r.user.userId;
    conditions.push(`O.customer_objid IN ($${i++}, $${i++})`);
    params.push(own, r.user.userId);
  } else if (customerObjid) {
    conditions.push(`O.customer_objid = $${i++}`);
    params.push(customerObjid);
  }

  if (Array.isArray(statuses) && statuses.length > 0) {
    const ph = statuses.map(() => `$${i++}`).join(",");
    conditions.push(`O.status IN (${ph})`);
    params.push(...statuses);
  } else if (status) {
    conditions.push(`O.status = $${i++}`);
    params.push(status);
  }
  if (dateFrom) {
    conditions.push(`O.order_date >= $${i++}::date`);
    params.push(dateFrom);
  }
  if (dateTo) {
    conditions.push(`O.order_date <= $${i++}::date`);
    params.push(dateTo);
  }
  if (keyword && keyword.trim()) {
    conditions.push(`(O.order_no ILIKE '%' || $${i} || '%' OR U.user_name ILIKE '%' || $${i} || '%' OR U.email ILIKE '%' || $${i} || '%')`);
    params.push(keyword.trim());
    i++;
  }

  const rows = await queryRows(
    `SELECT
       O.objid           AS "OBJID",
       O.order_no        AS "ORDER_NO",
       TO_CHAR(O.order_date, 'YYYY-MM-DD') AS "ORDER_DATE",
       O.customer_objid  AS "CUSTOMER_OBJID",
       U.user_name    AS "COMPANY_NAME",
       U.email           AS "EMAIL",
       O.status          AS "STATUS",
       O.total_supply    AS "TOTAL_SUPPLY",
       O.total_vat       AS "TOTAL_VAT",
       O.total_amount    AS "TOTAL_AMOUNT",
       O.total_taxfree   AS "TOTAL_TAXFREE",
       O.total_taxable   AS "TOTAL_TAXABLE",
       O.invoice_no      AS "INVOICE_NO",
       TO_CHAR(O.invoice_date, 'YYYY-MM-DD') AS "INVOICE_DATE",
       O.paid_amount     AS "PAID_AMOUNT",
       TO_CHAR(O.approve_date, 'YYYY-MM-DD HH24:MI') AS "APPROVE_DATE",
       O.memo            AS "MEMO",
       -- 편집 락 (2분 이내 갱신만 유효)
       CASE WHEN COALESCE(O.editing_at, 'epoch'::timestamp) > NOW() - INTERVAL '2 minutes'
            THEN O.editing_by ELSE NULL END     AS "EDITING_BY",
       CASE WHEN COALESCE(O.editing_at, 'epoch'::timestamp) > NOW() - INTERVAL '2 minutes'
            THEN E.user_name ELSE NULL END      AS "EDITING_BY_NAME"
     FROM momo_orders O
     LEFT JOIN user_info U ON U.user_id = O.customer_objid
     LEFT JOIN user_info E ON E.user_id = O.editing_by
     WHERE ${conditions.join(" AND ")}
     ORDER BY O.order_date DESC, O.regdate DESC
     LIMIT 500`,
    params
  );
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
