import { createServerClient, type CookieOptions } from '@supabase/ssr'
import type { Database } from './database.types'
import type { AstroCookies } from 'astro'

export function createSupabaseServerClient(
  cookies: AstroCookies,
  cookieOptions?: CookieOptions
) {
  // Environment-aware cookie configuration
  const isProduction = import.meta.env.PROD || process.env.NODE_ENV === 'production';
  
  // For Docker/localhost/IP addresses, always use non-secure cookies
  // In production, this will be overridden to use secure cookies
  const useSecureCookies = false; // Always false for Docker/network testing
  
  console.log('[SUPABASE SSR] Cookie config:', {
    isProduction,
    useSecureCookies,
    url: import.meta.env.PUBLIC_SUPABASE_URL
  });
  
  const defaultCookieOptions: CookieOptions = {
    secure: useSecureCookies,       // secure in production, non-secure for localhost
    sameSite: 'lax',               // allow cross-site cookie on navigation  
    path: '/',                     // root-wide access
    httpOnly: true,                // JS-inaccessible for security
    maxAge: 60 * 60 * 24 * 7,      // 7 days
    domain: undefined,             // Don't set domain for IP address compatibility
  };

  return createServerClient<Database>(
    import.meta.env.PUBLIC_SUPABASE_URL!,
    import.meta.env.PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        get(name: string) {
          if (!cookies) return undefined;
          return cookies.get(name)?.value
        },
        set(name: string, value: string, options: CookieOptions) {
          if (!cookies) return;
          // Merge with default options, allowing overrides
          const finalOptions = {
            ...defaultCookieOptions,
            ...cookieOptions,
            ...options,
          };
          console.log('[SUPABASE] Setting cookie:', {
            name,
            value: value ? '***' : 'empty',
            options: finalOptions
          });
          cookies.set(name, value, finalOptions);
        },
        remove(name: string, options: CookieOptions) {
          if (!cookies) return;
          cookies.delete(name, {
            ...defaultCookieOptions,
            ...options,
          })
        },
      },
      cookieOptions: defaultCookieOptions,
    }
  )
}

// Helper to create a client from Request headers (for API routes)
export function createSupabaseServerClientFromRequest(request: Request) {
  const cookieHeader = request.headers.get('Cookie') || ''
  
  return createServerClient<Database>(
    import.meta.env.PUBLIC_SUPABASE_URL!,
    import.meta.env.PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        get(name: string) {
          const cookies = parseCookies(cookieHeader)
          return cookies[name]
        },
        set() {
          // Can't set cookies in request context
        },
        remove() {
          // Can't remove cookies in request context
        },
      },
    }
  )
}

function parseCookies(cookieHeader: string): Record<string, string> {
  return cookieHeader.split(';').reduce((acc, cookie) => {
    const [key, value] = cookie.trim().split('=')
    if (key && value) {
      acc[key] = decodeURIComponent(value)
    }
    return acc
  }, {} as Record<string, string>)
}