import {
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
  signOut,
  updateProfile,
} from 'firebase/auth';
import { serverTimestamp, setDoc } from 'firebase/firestore';

import { auth } from '@/lib/firebase';
import { userDocRef } from '@/lib/firestore';

type RegisterParams = {
  email: string;
  password: string;
  username: string;
};

export async function loginWithEmail(email: string, password: string) {
  return signInWithEmailAndPassword(auth, email.trim(), password);
}

export async function registerWithEmail({
  email,
  password,
  username,
}: RegisterParams) {
  const normalizedEmail = email.trim();
  const normalizedUsername = username.trim();

  const credential = await createUserWithEmailAndPassword(
    auth,
    normalizedEmail,
    password
  );

  await updateProfile(credential.user, {
    displayName: normalizedUsername,
  });

  await setDoc(userDocRef(credential.user.uid), {
    uid: credential.user.uid,
    email:  normalizedEmail,
    username: normalizedUsername,
    profilePicture: credential.user.photoURL,
    expoPushTokens: [],
    createdAt: serverTimestamp(),
    updatedAt: serverTimestamp(),
  });

  return credential;
}

export async function logout() {
  return signOut(auth);
}
