"use client";

import { useState, useEffect } from "react";
import { User } from "@/types/types";
import useAxios from "./useAxios";
import { getStoredUserId, isAuthenticated } from "@/lib/auth/session";

function readStoredUser(): User | undefined {
  const id = getStoredUserId();
  if (!id) return undefined;
  return { _id: id } as User;
}

export const useUser = () => {
  const [user, setUser] = useState<User | undefined>(readStoredUser);
  const { request } = useAxios();
  const fetchUser = async () => {
    try {
      const response = await request<{ user: User }>("GET", "/profile");
      setUser(response?.user);
    } catch (error) {
      console.error("Failed to fetch user:", error);
    }
  };
  useEffect(() => {
    // مهمان پروفایل شخصی ندارد؛ از فچ بی‌مورد /profile جلوگیری می‌شود
    if (!isAuthenticated()) return;
    fetchUser();
  }, []);

  return user;
};
