import { getFirestore, doc, getDoc } from "firebase/firestore";
import { app } from "../features/auth/firebase";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - generated dataconnect types may not be resolvable in this context
import { getUserById } from "@/dataconnect-generated";

export interface UserData {
  id: string;
  email: string;
  fullName?: string;
  // role may come back uppercase or lowercase from the backend; treat as optional
  userRole?: "admin" | "client" | "vendor" | "ADMIN" | "CLIENT" | "VENDOR";
  photoURL?: string;
}

const db = getFirestore(app);

/**
 * Fetch user data from DataConnect (fallback to Firestore if needed)
 * @param uid - Firebase User UID
 * @returns UserData object with role information
 */
export const fetchUserData = async (uid: string): Promise<UserData | null> => {
  try {
    // Prefer backend dataconnect query for authoritative user role
    const { data } = await getUserById({ id: uid });

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const dataAny = data as any;

    if (dataAny && dataAny.user) {
      const user = dataAny.user;

      return {
        id: uid,
        email: user.email || "",
        fullName: user.fullName,
        userRole: user.userRole,
        photoURL: user.photoUrl || user.photoURL,
      };
    }

    // Fallback: attempt Firestore lookup if dataconnect didn't return a user
    const userDocRef = doc(db, "users", uid);
    const userDocSnap = await getDoc(userDocRef);

    if (userDocSnap.exists()) {
      const data = userDocSnap.data();
      return {
        id: uid,
        email: data.email || "",
        fullName: data.fullName,
        userRole: data.userRole, // no frontend defaulting
        photoURL: data.photoURL,
      };
    }

    return null;
  } catch (error) {
    console.error("Error fetching user data from DataConnect/Firestore:", error);
    throw error;
  }
};

/**
 * Get the dashboard path for a given user role
 * @param userRole - The user's role
 * @returns The appropriate dashboard path
 */
export const getDashboardPath = (userRole: string): string => {
  const roleMap: Record<string, string> = {
    admin: "/dashboard/admin",
    client: "/dashboard/client",
    vendor: "/dashboard/vendor",
  };

  return roleMap[userRole.toLowerCase()] || "/dashboard/client";
};
