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

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

  let body: { masterObjid?: string | number; userIds?: string[] } = {};
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ success: false, message: "잘못된 요청" }, { status: 400 });
  }

  const { masterObjid, userIds } = body;
  if (!masterObjid || !userIds || !Array.isArray(userIds) || userIds.length === 0) {
    return NextResponse.json({ success: false, message: "대상을 선택하세요." }, { status: 400 });
  }

  let added = 0;
  const errors: string[] = [];
  for (const userId of userIds) {
    try {
      const objid = createObjectId();
      const rowCount = await execute(
        `INSERT INTO AUTHORITY_SUB_USER (OBJID, MASTER_OBJID, USER_ID, WRITER, REGDATE)
         SELECT $1::numeric, $2::numeric, $3::text, $4::text, now()
         WHERE NOT EXISTS (
           SELECT 1 FROM AUTHORITY_SUB_USER WHERE USER_ID = $3::text AND MASTER_OBJID = $2::numeric
         )`,
        [objid, masterObjid, userId, user.userId]
      );
      if (rowCount > 0) {
        added++;
        // 이력 — 테이블이 없거나 컬럼이 달라도 메인 동작은 살아남도록 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)
             VALUES ($1::numeric, $2::numeric,
               (SELECT AUTH_NAME FROM AUTHORITY_MASTER WHERE OBJID = $2::numeric),
               (SELECT AUTH_CODE FROM AUTHORITY_MASTER WHERE OBJID = $2::numeric),
               $3,
               (SELECT STATUS FROM AUTHORITY_MASTER WHERE OBJID = $2::numeric),
               'ADD', $4, now())`,
            [createObjectId(), masterObjid, userId, user.userId]
          );
        } catch (histErr) {
          console.warn("[auth/members/save] history insert skipped:", histErr instanceof Error ? histErr.message : histErr);
        }
      }
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      console.error(`[auth/members/save] userId=${userId} 실패:`, msg);
      errors.push(`${userId}: ${msg}`);
    }
  }

  if (added === 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
      ? `${added}명 추가 / ${errors.length}건 실패`
      : `${added}명이 추가되었습니다.`,
    errors,
  });
}
