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

// 권한그룹 멤버 삭제 (deleteAuthorityMember 대응)
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  let body: { masterObjid?: string | number; memberObjids?: (string | number)[] } = {};
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ success: false, message: "잘못된 요청" }, { status: 400 });
  }
  const { masterObjid, memberObjids } = body;
  if (!masterObjid || !memberObjids || !Array.isArray(memberObjids) || memberObjids.length === 0) {
    return NextResponse.json({ success: false, message: "대상을 선택하세요." }, { status: 400 });
  }

  let removed = 0;
  const errors: string[] = [];
  for (const memberObjid of memberObjids) {
    // 이력 — best-effort
    try {
      await execute(
        `INSERT INTO AUTHORITY_MASTER_HISTORY (OBJID, PARENT_OBJID, PARENT_NAME, PARENT_CODE, USER_ID, ACTIVE, HISTORY_TYPE, WRITER, REG_DATE)
         SELECT $1::numeric, $2::numeric,
           (SELECT AUTH_NAME FROM AUTHORITY_MASTER WHERE OBJID = $2::numeric),
           (SELECT AUTH_CODE FROM AUTHORITY_MASTER WHERE OBJID = $2::numeric),
           ASU.USER_ID,
           (SELECT STATUS FROM AUTHORITY_MASTER WHERE OBJID = $2::numeric),
           'REMOVE', $3, now()
         FROM AUTHORITY_SUB_USER ASU WHERE ASU.OBJID = $4::numeric`,
        [createObjectId(), masterObjid, user.userId, memberObjid]
      );
    } catch (histErr) {
      console.warn("[auth/members/delete] history insert skipped:", histErr instanceof Error ? histErr.message : histErr);
    }
    try {
      // text 비교 — OBJID 가 numeric/text 어느 쪽이든 안정적으로 매칭 (silent 0건 방지)
      const rc = await execute(
        `DELETE FROM AUTHORITY_SUB_USER WHERE MASTER_OBJID::text = $1 AND OBJID::text = $2`,
        [String(masterObjid), String(memberObjid)]
      );
      if (rc > 0) removed++;
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      console.error(`[auth/members/delete] memberObjid=${memberObjid} 실패:`, msg);
      errors.push(`${memberObjid}: ${msg}`);
    }
  }

  if (removed === 0 && errors.length > 0) {
    return NextResponse.json({
      success: false,
      message: `삭제 실패 (${errors.length}건): ${errors[0]}`,
    }, { status: 500 });
  }
  return NextResponse.json({
    success: true,
    message: errors.length > 0
      ? `${removed}명 제거 / ${errors.length}건 실패`
      : `${removed}명이 제거되었습니다.`,
    errors,
  });
}
