import { createClient } from '@supabase/supabase-js'
import { auth } from '@clerk/nextjs/server'
import { Database } from '@/types/supabase'

// Initialize the Supabase client
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!

export const getSupabaseClient = async () => {
    const { getToken } = auth()

    const supabaseAccessToken = await getToken({ template: 'supabase' })
    if (supabaseAccessToken) {
        console.log("Token decodes to:", JSON.parse(Buffer.from(supabaseAccessToken.split('.')[1], 'base64').toString()));
    }

    const supabase = createClient<Database>(
        supabaseUrl,
        supabaseAnonKey,
        {
            global: {
                headers: {
                    Authorization: `Bearer ${supabaseAccessToken}`,
                },
            },
        }
    )

    return supabase
}
