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

// 권한그룹 등록/수정 (mergeAuthorityMaster 대응)
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  try {
    const body = await request.json();
    const objid = body.objid || createObjectId();

    // 신규 등록 시 권한CODE 자동 생성 (사용자에게 노출하지 않고 내부 식별자만 유지)
    let authCode = (body.auth_code || "").trim();
    if (!body.objid && !authCode) {
      authCode = `GRP_${Date.now().toString(36).toUpperCase()}`;
    }

    await execute(
      `INSERT INTO AUTHORITY_MASTER (OBJID, AUTH_NAME, AUTH_CODE, WRITER, REGDATE, STATUS)
       VALUES ($1::numeric, $2, $3, $4, now(), $5)
       ON CONFLICT (OBJID) DO UPDATE
       SET AUTH_NAME = $2, AUTH_CODE = COALESCE(NULLIF($3, ''), AUTHORITY_MASTER.AUTH_CODE), STATUS = $5`,
      [objid, body.auth_name || "", authCode, user.userId, body.status || "active"]
    );

    return NextResponse.json({ success: true, message: body.objid ? "수정되었습니다." : "등록되었습니다.", objid });
  } catch (error) {
    console.error("Auth save:", error);
    return NextResponse.json({ success: false, message: "처리 중 오류가 발생했습니다." }, { status: 500 });
  }
}
