import { TLUserPreferences } from '@tldraw/tldraw';
import { supabase } from '../../supabaseClient';
import { logger } from '../../debugConfig';
import { CCUser } from './authService';

export type UserProfile = CCUser;

export interface UserProfileUpdate extends Partial<UserProfile> {
  id: string; // ID is always required for updates
}

export interface UserPreferences {
  tldraw?: TLUserPreferences;
  theme?: 'light' | 'dark' | 'system';
  notifications?: boolean;
}

export async function createUserProfile(profile: UserProfile): Promise<UserProfile | null> {
  try {
    const { data, error } = await supabase
      .from('profiles')
      .insert([profile])
      .select()
      .single();

    if (error) {
      logger.error('supabase-profile-service', '❌ Failed to create user profile', { 
        userId: profile.id,
        error 
      });
      throw error;
    }

    return data;
  } catch (error) {
    logger.error('supabase-profile-service', '❌ Error in createUserProfile', error);
    return null;
  }
}

export async function getUserProfile(userId: string): Promise<UserProfile | null> {
  try {
    const { data, error } = await supabase
      .from('profiles')
      .select('*')
      .eq('id', userId)
      .single();

    if (error) {
      logger.error('supabase-profile-service', '❌ Failed to fetch user profile', { 
        userId,
        error 
      });
      throw error;
    }

    return data;
  } catch (error) {
    logger.error('supabase-profile-service', '❌ Error in getUserProfile', error);
    return null;
  }
}

export async function updateUserProfile(update: UserProfileUpdate): Promise<UserProfile | null> {
  try {
    const { data, error } = await supabase
      .from('profiles')
      .update(update)
      .eq('id', update.id)
      .select()
      .single();

    if (error) {
      logger.error('supabase-profile-service', '❌ Failed to update user profile', { 
        userId: update.id,
        error 
      });
      throw error;
    }

    return data;
  } catch (error) {
    logger.error('supabase-profile-service', '❌ Error in updateUserProfile', error);
    return null;
  }
}
