"use client";

import { createContext, useContext, useEffect, useState } from "react";

type User = {
  firstName: string;
  lastName: string;
  email: string;
} | null;

type AuthContextType = {
  user: User;
  setUser: (user: User) => void;
};

const AuthContext = createContext<AuthContextType>({
  user: null,
  setUser: () => {},
});

export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
  const [user, setUser] = useState<User>(null);

  useEffect(() => {
    // Fetch user data if already logged in
    const fetchUser = async () => {
      try {
        const res = await fetch(
          "https://milimanibackend.sigraelfasolutions.com/api/auth/me",
          {
            credentials: "include",
          }
        );
        if (res.ok) {
          const data = await res.json();
          setUser(data.user);
        }
      } catch (err) {
        console.error("Error fetching user:", err);
      }
    };
    fetchUser();
  }, []);

  return (
    <AuthContext.Provider value={{ user, setUser }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => useContext(AuthContext);
