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

// 계약 삭제 (contractMgmt.deleteContractMngInfo 대응)
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 { objIds } = body;

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

  try {
    // 수주 상태인 건은 삭제 불가
    const placeholders = objIds.map((_: string, i: number) => `$${i + 1}`).join(",");

    // 첨부파일도 함께 삭제
    await execute(
      `DELETE FROM attach_file_info WHERE target_objid IN (${objIds.map((_: string, i: number) => `$${i + 1}`).join(",")})`,
      objIds
    );

    // 계약 삭제
    await execute(
      `DELETE FROM contract_mgmt WHERE objid IN (${placeholders})`,
      objIds
    );

    return NextResponse.json({ success: true, message: `${objIds.length}건이 삭제되었습니다.` });
  } catch (error) {
    console.error("Contract delete error:", error);
    return NextResponse.json({ success: false, message: "삭제 중 오류가 발생했습니다." });
  }
}
