import {
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
  sendPasswordResetEmail,
  reauthenticateWithCredential,
  updatePassword,
  EmailAuthProvider,
  signOut,
} from "firebase/auth";
import { auth } from "@/lib/firebase";

/** Email + password → Firebase UID (or throws on wrong credentials) */
export async function firebaseEmailSignIn(
  email: string,
  password: string,
): Promise<string> {
  const cred = await signInWithEmailAndPassword(auth, email, password);
  return cred.user.uid;
}

/**
 * Create a new Firebase account.
 * If the email is already registered, falls back to sign-in (same UID returned).
 */
export async function firebaseCreateAccount(
  email: string,
  password: string,
): Promise<string> {
  try {
    const cred = await createUserWithEmailAndPassword(auth, email, password);
    return cred.user.uid;
  } catch (err: unknown) {
    const code = (err as { code?: string })?.code;
    if (code === "auth/email-already-in-use") {
      const cred = await signInWithEmailAndPassword(auth, email, password);
      return cred.user.uid;
    }
    throw err;
  }
}

/**
 * Re-authenticate with the current password, then update to the new one.
 * Keeps Firebase in sync with the backend whenever a signed-in user changes
 * their own password — throws (with the original Firebase error code) if
 * `currentPassword` doesn't match Firebase's record, e.g. an account left
 * out of sync by an out-of-band backend-only password change.
 */
export async function firebaseUpdatePassword(
  email: string,
  currentPassword: string,
  newPassword: string,
): Promise<void> {
  const user = auth.currentUser;
  if (!user) throw new Error("No active Firebase session.");

  const credential = EmailAuthProvider.credential(email, currentPassword);
  await reauthenticateWithCredential(user, credential);
  await updatePassword(user, newPassword);
}

/** Firebase password-reset email — no backend needed */
export async function firebasePasswordReset(email: string): Promise<void> {
  await sendPasswordResetEmail(auth, email);
}

export async function signOutFromFirebase(): Promise<void> {
  try {
    await signOut(auth);
  } catch (err) {
    console.error("[Firebase Auth] signOut failed:", err);
  }
}
