import { createServerClient } from "@supabase/ssr";
import { createClient as createSupabaseClient } from "@supabase/supabase-js";
import { cookies } from "next/headers";

/**
 * Cookie-based server client WITH user context.
 * Use this in Server Components, Server Actions, and Route Handlers
 * where you need to know who the logged-in user is.
 */
export async function createClient() {
  const cookieStore = await cookies();

  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() {
          return cookieStore.getAll();
        },
        setAll(cookiesToSet) {
          try {
            cookiesToSet.forEach(({ name, value, options }) =>
              cookieStore.set(name, value, options)
            );
          } catch {
            // Cookies can only be set in Server Actions or Route Handlers
          }
        },
      },
    }
  );
}

/**
 * Admin client with service key — bypasses RLS.
 * Use ONLY for admin operations (email verification, etc.)
 * NEVER use this to read user data in server components.
 * Gracefully handles missing SUPABASE_SERVICE_KEY.
 */
function createAdminClient() {
  const serviceKey = process.env.SUPABASE_SERVICE_KEY;
  if (!serviceKey) {
    console.warn(
      'SUPABASE_SERVICE_KEY is not set. Admin operations will not work. ' +
      'Set SUPABASE_SERVICE_KEY in your environment variables.'
    );
    return null;
  }

  return createSupabaseClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    serviceKey,
    {
      auth: {
        autoRefreshToken: false,
        persistSession: false,
      },
    }
  );
}

export const supabaseAdmin = createAdminClient();

/**
 * Service client factory for route handlers that need admin access.
 */
export function createServiceClient() {
  const client = createAdminClient();
  if (!client) {
    throw new Error('SUPABASE_SERVICE_KEY is not configured. Cannot create service client.');
  }
  return client;
}

/**
 * Helper to verify email addresses (admin operation)
 */
export async function verifyEmail(userId: string) {
  if (!supabaseAdmin) {
    throw new Error('Admin client not available. SUPABASE_SERVICE_KEY is not set.');
  }

  const { data, error } = await supabaseAdmin.auth.admin.updateUserById(
    userId,
    { email_confirm: true }
  );

  if (error) throw error;
  return data;
}

/**
 * Helper to check if user has verified their email (admin operation)
 */
export async function isEmailVerified(userId: string): Promise<boolean> {
  if (!supabaseAdmin) {
    console.warn('Admin client not available. Cannot check email verification status.');
    return false;
  }

  const { data, error } = await supabaseAdmin.auth.admin.getUserById(userId);

  if (error) return false;
  return !!data.user?.email_confirmed_at;
}
