import { useAuth } from '@/profile/auth/context';
import { ProfileRepository, type ProfileRow } from '@/profile/repository';
import { useQuery } from '@/remote/database';
import type { UserProfile } from '@/types/foodlog';
import { createContext, useContext, type ReactNode } from 'react';

type ProfileContextType = {
  profile: UserProfile | null;
  isLoading: boolean;
};

const ProfileContext = createContext<ProfileContextType>({ profile: null, isLoading: true });

export function ProfileProvider({ children }: { children: ReactNode }) {
  const { user } = useAuth();
  const { data: rows, isLoading } = useQuery<ProfileRow>(
    'SELECT * FROM profiles WHERE workos_user_id = ? LIMIT 1',
    [user?.id ?? '']
  );

  const profile = user?.id && rows?.[0] ? ProfileRepository.mapRowToProfile(rows[0]) : null;

  return (
    <ProfileContext.Provider value={{ profile, isLoading: user ? isLoading : false }}>
      {children}
    </ProfileContext.Provider>
  );
}

export function useProfile() {
  return useContext(ProfileContext);
}
