// 부서 진짜 삭제 (DELETE)
import { NextRequest, NextResponse } from "next/server";
import { pool, queryOne } 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 { deptCode, deptCodes } = await req.json() as { deptCode?: string; deptCodes?: string[] };
  const targets = deptCodes && deptCodes.length > 0 ? deptCodes : (deptCode ? [deptCode] : []);
  if (targets.length === 0) {
    return NextResponse.json({ success: false, message: "삭제할 부서를 선택하세요." }, { status: 400 });
  }
  const ph = targets.map((_, i) => `$${i + 1}`).join(",");

  // 자식 부서/소속 사용자 검사 (status 무관, 진짜 row 존재 여부)
  const child = await queryOne<{ cnt: string }>(
    `SELECT COUNT(*) AS cnt FROM dept_info WHERE parent_dept_code IN (${ph})`,
    targets
  );
  if (Number(child?.cnt || 0) > 0) {
    return NextResponse.json({ success: false, message: `하위 부서 ${child!.cnt}개가 있어 삭제할 수 없습니다.` }, { status: 400 });
  }
  const userCnt = await queryOne<{ cnt: string }>(
    `SELECT COUNT(*) AS cnt FROM user_info WHERE dept_code IN (${ph})`,
    targets
  );
  if (Number(userCnt?.cnt || 0) > 0) {
    return NextResponse.json({ success: false, message: `소속 사용자 ${userCnt!.cnt}명이 있어 삭제할 수 없습니다.` }, { status: 400 });
  }

  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const r = await client.query(`DELETE FROM dept_info WHERE dept_code IN (${ph})`, targets);
    await client.query("COMMIT");
    return NextResponse.json({ success: true, deleted: r.rowCount });
  } catch (e) {
    await client.query("ROLLBACK");
    console.error("Dept delete:", e);
    const msg = e instanceof Error ? e.message : "삭제 실패";
    return NextResponse.json({ success: false, message: msg }, { status: 500 });
  } finally {
    client.release();
  }
}
