// import { createServerClient, type CookieOptions } from "@supabase/ssr"
// import { cookies } from "next/headers"
// import { getRuntimeEnv } from "@/lib/ipconfig"
// import { Database } from "@/supabase/types"

// export function getSupabaseServerClient() {
//   const supabaseUrl = getRuntimeEnv("SUPABASE_URL") ?? "http://localhost:8000"
//   const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!

//   const cookieStore = cookies()

//   return createServerClient<Database>(supabaseUrl, supabaseAnonKey, {
//     cookies: {
//       get(name: string) {
//         return cookieStore.get(name)?.value
//       },
//       set(name: string, value: string, options: CookieOptions) {
//         try {
//           cookieStore.set({ name, value, ...options })
//         } catch (_) {}
//       },
//       remove(name: string, options: CookieOptions) {
//         try {
//           cookieStore.set({ name, value: "", ...options })
//         } catch (_) {}
//       }
//     }
//   })
// }



// lib/supabase-server.ts
import { createServerClient, type CookieOptions } from "@supabase/ssr"
import { cookies } from "next/headers"
import { getRuntimeEnv } from "@/lib/get-runtime-env"          // ← 改成新的工具函数
import { Database } from "@/supabase/types"

export function getSupabaseServerClient() {
  /* ① URL：优先 RuntimeEnv（由 RuntimeEnvProvider 注入），
        然后退回到 .env，最后兜底 localhost  */
  const supabaseUrl =
    getRuntimeEnv("SUPABASE_URL") ??
    process.env.SUPABASE_URL ??
    "http://localhost:8000"

  /* ② 匿名 KEY 只放 .env，别暴露到 RuntimeEnv */
  const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
  if (!supabaseAnonKey) {
    throw new Error("⛔️ NEXT_PUBLIC_SUPABASE_ANON_KEY 未设置")
  }

  /* ③ Cookie 透传（Next 13/14 App Router 写法） */
  const cookieStore = cookies()

  return createServerClient<Database>(supabaseUrl, supabaseAnonKey, {
    cookies: {
      get(name: string) {
        return cookieStore.get(name)?.value
      },
      set(name: string, value: string, options: CookieOptions) {
        try {
          cookieStore.set({ name, value, ...options })
        } catch {}
      },
      remove(name: string, options: CookieOptions) {
        try {
          cookieStore.set({ name, value: "", ...options })
        } catch {}
      }
    }
  })
}
