import type { SignInWithPasswordCredentials } from '@supabase/supabase-js';

import { useMutation } from '@tanstack/react-query';

import { medusaLoginOrRegister } from '../../../features/medusa-storefront/src/lib/data/customer';
import { useSupabase } from './use-supabase';

export function useSignInWithEmailPassword() {
  const client = useSupabase();
  const mutationKey = ['auth', 'sign-in-with-email-password'];

  const mutationFn = async (credentials: SignInWithPasswordCredentials) => {
    const response = await client.auth.signInWithPassword(credentials);

    if (response.error) {
      throw response.error.message;
    }

    const user = response.data?.user;
    const identities = user?.identities ?? [];

    if (identities.length === 0) {
      throw new Error('Invalid user');
    }

    if ('email' in credentials) {
      try {
        const medusaAccountId = await medusaLoginOrRegister({
          email: credentials.email,
          password: credentials.password,
          isDevPasswordLogin: true,
        });
        await client
          .schema('medreport')
          .from('accounts')
          .update({ medusa_account_id: medusaAccountId })
          .eq('primary_owner_user_id', user.id)
          .eq('is_personal_account', true);
      } catch (error) {
        await client.auth.signOut();
        throw error;
      }
    }

    return response.data;
  };

  return useMutation({ mutationKey, mutationFn });
}
