import pkg from '@supabase/ssr';
const { createServerClient } = pkg;
import { createClient as createSupabaseClient } from '@supabase/supabase-js';
import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public';
import { SUPABASE_SERVICE_ROLE_KEY } from '$env/static/private';
import { env } from '$env/dynamic/private';
import type { Cookies } from '@sveltejs/kit';
import type { Database } from '$lib/types/database';

// Use internal URL for server-side operations (Docker network), fallback to public URL
const SERVER_SUPABASE_URL = env.SUPABASE_INTERNAL_URL || PUBLIC_SUPABASE_URL;

/**
 * Create a Supabase client for server-side operations with cookie handling
 */
export function createSupabaseServerClient(cookies: Cookies) {
	return createServerClient<Database>(SERVER_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY, {
		cookies: {
			getAll: () => cookies.getAll(),
			setAll: (cookiesToSet) => {
				cookiesToSet.forEach(({ name, value, options }) => {
					cookies.set(name, value, { ...options, path: '/' });
				});
			}
		}
	});
}

/**
 * Supabase Admin client with service role key
 * Use this for administrative operations that bypass RLS
 */
export const supabaseAdmin = createSupabaseClient<Database>(
	SERVER_SUPABASE_URL,
	SUPABASE_SERVICE_ROLE_KEY,
	{
		auth: {
			autoRefreshToken: false,
			persistSession: false
		}
	}
);
