import { useTypedSelector } from "../redux/rootReducer";
import { selectUserData } from "../redux/User/selector";
import { User } from "../redux/User/types";

type UserAccountDetails = {
  id?: number;
  fullname?: string;
  email?: string;
  createdAt?: number; // epoch milli timestamp
};

export function useUserAccountDetails(): UserAccountDetails | undefined {
  const user = useTypedSelector(selectUserData);

  if (!user) {
    return undefined;
  }

  const createdAt = user.createdAt ? new Date(user.createdAt) : undefined;

  return {
    id: user.id,
    fullname: fullname(user),
    email: user.email,
    createdAt: createdAt?.getTime(),
  };
}

function fullname(user: User) {
  if (!user.firstName && !user.lastName) {
    return undefined;
  }

  const firstName = user.firstName ?? "";
  const lastName = user.lastName ?? "";

  return `${firstName} ${lastName}`.trim();
}
