import { createServerClient } from "@supabase/ssr"
import { createServerOnlyFn } from "@tanstack/react-start"
import { getCookies, setCookie } from "@tanstack/react-start/server"

const supabase_url = createServerOnlyFn(
	() => process.env.VITE_SUPABASE_URL as string
)
const supabase_key = createServerOnlyFn(
	() => process.env.VITE_SUPABASE_KEY as string
)

export function getSupabaseServerClient() {
	return createServerClient(supabase_url(), supabase_key(), {
		cookies: {
			getAll() {
				return Object.entries(getCookies()).map(([name, value]) => ({
					name,
					value
				}))
			},
			setAll(cookies) {
				cookies.forEach((cookie) => {
					setCookie(cookie.name, cookie.value)
				})
			}
		}
	})
}
