import * as SecureStore from 'expo-secure-store';

type UserData = {
  id: number;
  appleId: string | null;
  appleEmail: string | null;
  fullName: string;
  pfpURL: string | null;
  pushToken: string;
  createdAt: Date;
};

export const saveUserData = async (userData: UserData) => {
  try {
    await SecureStore.setItemAsync('userData', JSON.stringify(userData));
  } catch (error) {
    console.error('Error saving user data:', error);
  }
};

export const getUserData = async () => {
  try { 
    const userData = await SecureStore.getItemAsync('userData');
    return userData ? JSON.parse(userData) : null;
  } catch (error) {
    console.error('Error getting user data:', error);
    return null;
  }
};

export const updateUserData = async (updatedFields: Partial<any>) => {
  try {
    const currentUserData: UserData = await getUserData() as UserData;
    if (currentUserData) {
      const updatedUserData: UserData = { ...currentUserData, ...updatedFields };
      await saveUserData(updatedUserData);
      return updatedUserData as UserData;
    }
    return null;
  } catch (error) {
    console.error('Error updating user data:', error);
    return null;
  }
};
