import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

// This check can be removed, it is just for tutorial purposes
export const hasEnvVars =
  (process.env.SUPABASE_URL || process.env.NEXT_PUBLIC_SUPABASE_URL) &&
  (process.env.SUPABASE_ANON_KEY ||
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY ||
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY);

export function resolveSupabaseUrl(url: string | undefined): string | undefined {
  if (!url) return url;
  if (typeof window !== 'undefined') {
    try {
      const parsed = new URL(url);
      if (parsed.hostname === 'supabase-kong' || parsed.hostname === 'kong') {
        parsed.hostname = window.location.hostname;
        parsed.protocol = window.location.protocol;
        parsed.port = ''; // Port entfernen, da der öffentliche Zugriff über Port 80/443 läuft
        return parsed.toString().replace(/\/$/, '');
      }
      
      // Mitigate Mixed Content: if the site is HTTPS, force Supabase to HTTPS
      if (window.location.protocol === 'https:' && parsed.protocol === 'http:') {
        parsed.protocol = 'https:';
        return parsed.toString().replace(/\/$/, '');
      }
    } catch {
      let resolved = url
        .replace('//supabase-kong:8000', `//${window.location.hostname}`)
        .replace('//kong:8000', `//${window.location.hostname}`)
        .replace('//supabase-kong', `//${window.location.hostname}`)
        .replace('//kong', `//${window.location.hostname}`);
      if (window.location.protocol === 'https:') {
        resolved = resolved.replace('http://', 'https://');
      }
      return resolved;
    }
  }
  return url;
}
