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

// 원본: deleteSalesLongDelivery — 자식 테이블 + 메인 모두 삭제
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const { objIds } = await request.json();
  if (!Array.isArray(objIds) || objIds.length === 0) {
    return NextResponse.json({ success: false, message: "삭제할 항목을 선택하세요." });
  }

  const ph = objIds.map((_: string, i: number) => `$${i + 1}`).join(",");
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    await client.query(`DELETE FROM sales_long_delivery_input WHERE parent_objid IN (${ph})`, objIds);
    await client.query(`DELETE FROM sales_long_delivery_predict WHERE parent_objid IN (${ph})`, objIds);
    await client.query(`DELETE FROM sales_long_delivery WHERE objid IN (${ph})`, objIds);
    await client.query("COMMIT");
    return NextResponse.json({ success: true, message: `${objIds.length}건이 삭제되었습니다.` });
  } catch (e) {
    await client.query("ROLLBACK");
    console.error("stock delete:", e);
    return NextResponse.json({ success: false, message: "삭제 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
