import pkg from '@supabase/ssr';
const { createServerClient } = pkg;
import { createClient as createSupabaseClient } from '@supabase/supabase-js';
import { env as publicEnv } from '$env/dynamic/public';
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
function getSupabaseUrl() {
	return env.SUPABASE_INTERNAL_URL || publicEnv.PUBLIC_SUPABASE_URL;
}
const SUPABASE_SERVICE_ROLE_KEY = env.SUPABASE_SERVICE_ROLE_KEY || '';

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

// Lazy-initialized admin client to ensure env vars are loaded
let _supabaseAdmin: ReturnType<typeof createSupabaseClient<Database>> | null = null;

/**
 * Supabase Admin client with service role key
 * Use this for administrative operations that bypass RLS
 */
export const supabaseAdmin = new Proxy({} as ReturnType<typeof createSupabaseClient<Database>>, {
	get(_, prop) {
		if (!_supabaseAdmin) {
			_supabaseAdmin = createSupabaseClient<Database>(
				getSupabaseUrl(),
				env.SUPABASE_SERVICE_ROLE_KEY || '',
				{
					auth: {
						autoRefreshToken: false,
						persistSession: false
					}
				}
			);
		}
		return (_supabaseAdmin as any)[prop];
	}
});
