import { supabase } from '../supabase.js';

/** Resolve email for login when user enters a username (display_name). Returns null if not found. */
export async function getEmailForUsername(username) {
  const trimmed = (username ?? '').trim();
  if (!trimmed) return null;
  const { data, error } = await supabase
    .from('profiles')
    .select('email')
    .ilike('display_name', trimmed)
    .limit(1);
  if (error || !data?.length || !data[0]?.email) return null;
  return data[0].email;
}

export async function getProfile(userId) {
  const { data, error } = await supabase
    .from('profiles')
    .select('id, display_name, email, avatar_url')
    .eq('id', userId)
    .single();
  if (error && error.code !== 'PGRST116') throw error;
  return data ?? null;
}

export async function updateProfile(userId, { display_name, avatar_url }) {
  const updates = {};
  if (display_name !== undefined) updates.display_name = display_name?.trim() || null;
  if (avatar_url !== undefined) updates.avatar_url = avatar_url || null;
  updates.updated_at = new Date().toISOString();

  const { data, error } = await supabase
    .from('profiles')
    .update(updates)
    .eq('id', userId)
    .select('id, display_name, email, avatar_url')
    .single();
  if (error) throw error;
  return data;
}

export function getAvatarPublicUrl(path) {
  const { data } = supabase.storage.from('avatars').getPublicUrl(path);
  return data?.publicUrl ?? '';
}

export async function uploadAvatar(userId, file) {
  const ext = file.name.split('.').pop()?.toLowerCase() || 'jpg';
  const path = `${userId}/avatar.${ext}`;
  const { error } = await supabase.storage.from('avatars').upload(path, file, {
    upsert: true,
    contentType: file.type,
  });
  if (error) throw error;
  return getAvatarPublicUrl(path);
}
