import {
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
  signOut,
} from "firebase/auth";
import { auth, FIREBASE_STATIC_PASSWORD } from "@/lib/firebase";

/**
 * Email → Firebase UID, using the shared static password (chat/UID only —
 * the backend is the source of truth for the user's real password).
 * Throws if this email has no Firebase account yet.
 */
export async function firebaseEmailSignIn(email: string): Promise<string> {
  const cred = await signInWithEmailAndPassword(auth, email, FIREBASE_STATIC_PASSWORD);
  return cred.user.uid;
}

/**
 * Create a new Firebase account with the shared static password.
 * If the email is already registered, falls back to sign-in (same UID returned).
 */
export async function firebaseCreateAccount(email: string): Promise<string> {
  try {
    const cred = await createUserWithEmailAndPassword(auth, email, FIREBASE_STATIC_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, FIREBASE_STATIC_PASSWORD);
      return cred.user.uid;
    }
    throw err;
  }
}

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