// 사용자 진짜 삭제 (DELETE) — 관련 매핑까지 정리
import { NextRequest, NextResponse } from "next/server";
import { pool } from "@/lib/db";
import { getSession } from "@/lib/session";

export async function POST(req: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });
  const { ids, userIds } = await req.json() as { ids?: string[]; userIds?: string[] };
  const targets = (userIds || ids || []).filter(Boolean);
  if (targets.length === 0) {
    return NextResponse.json({ success: false, message: "삭제할 사용자를 선택하세요." }, { status: 400 });
  }

  // 본인 자기 자신 삭제 방지
  if (targets.some((id) => String(id) === String(user.userId))) {
    return NextResponse.json({ success: false, message: "본인 계정은 삭제할 수 없습니다." }, { status: 400 });
  }

  const placeholders = targets.map((_, i) => `$${i + 1}`).join(",");
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    // 관련 매핑 정리 — FK 충돌 방지
    await client.query(`DELETE FROM authority_sub_user WHERE user_id IN (${placeholders})`, targets);
    // 실제 삭제
    const r = await client.query(`DELETE FROM user_info WHERE user_id IN (${placeholders})`, targets);
    await client.query("COMMIT");
    return NextResponse.json({ success: true, deleted: r.rowCount });
  } catch (e) {
    await client.query("ROLLBACK");
    console.error("Users delete:", e);
    const msg = e instanceof Error ? e.message : "삭제 실패";
    return NextResponse.json({ success: false, message: msg }, { status: 500 });
  } finally {
    client.release();
  }
}
