import { createClient } from "@supabase/supabase-js";

const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY;

export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
  global: {
    headers: {
      'x-application-name': 'cappadocia-travel',
    }
  }
});

/**
 * Sets the Clerk JWT token for the Supabase client.
 * This ensures that Supabase requests are made with the user's identity.
 */
export function setSupabaseToken(token: string | null): void {
  if (token) {
    // We are not using Supabase internal auth, just setting headers
    // @ts-ignore
    if (supabase.realtime) {
      // @ts-ignore
      supabase.realtime.setAuth(token);
    }
    // @ts-ignore
    if (supabase.rest && supabase.rest.headers) {
      // @ts-ignore
      supabase.rest.headers['Authorization'] = `Bearer ${token}`;
    }
  } else {
    // @ts-ignore
    if (supabase.rest && supabase.rest.headers) {
      // @ts-ignore
      delete supabase.rest.headers['Authorization'];
    }
  }
}
