// MOMO API 라우트 권한 가드 헬퍼
import { NextResponse } from "next/server";
import { getSession } from "./session";
import type { User } from "@/types";

export async function requireMomoUser(): Promise<{ user: User } | NextResponse> {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false, message: "로그인이 필요합니다." }, { status: 401 });
  // MOMO 가입자(role) + FITO 사용자 모두 통과
  return { user };
}

export async function requireMomoAdmin(): Promise<{ user: User } | NextResponse> {
  const r = await requireMomoUser();
  if (r instanceof NextResponse) return r;
  // ADMIN 판정:
  // - MOMO role==='ADMIN'
  // - FITO isAdmin===true (plm_admin)
  // - userType==='MOMO' or userType==='A' (user_info.user_type='A' 케이스)
  // - admin@momo.com 이메일
  const u = r.user;
  const isAdmin =
    u.role === "ADMIN" ||
    u.isAdmin === true ||
    u.userType === "A" ||
    u.userId?.toLowerCase() === "admin@momo.com";
  if (!isAdmin) {
    return NextResponse.json({ success: false, message: "관리자 권한이 필요합니다." }, { status: 403 });
  }
  return r;
}
