import { createContext, useState, useEffect, ReactNode } from 'react';
import Cookie from 'js-cookie';
import { axiosClient } from '@/utils/axiosClient';
import { UserType } from '@/types/types.ts';

type AuthContextType = {
  authorized: boolean | null;
  setAuthorized: (value: boolean) => void;
  user: UserType | null;
  setUser: (user: UserType | null) => void;
};

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

export function AuthProvider({ children }: { children: ReactNode }) {
  const [authorized, setAuthorized] = useState<boolean | null>(null);
  const [user, setUser] = useState<UserType | null>(null);

  useEffect(() => {
    async function validateToken() {
      const token = Cookie.get('token');
      if (!token) {
        setAuthorized(false);
        return;
      }

      try {
        const res = await axiosClient.get('/api/auth/validate', {
          withCredentials: true,
        });
        setUser({ username: res.data.username, id: res.data.user_id });
        console.info('user: : ', {
          username: res.data.username,
          id: res.data.user_id,
        });
        setAuthorized(true);
      } catch (err) {
        setAuthorized(false);
        setUser(null);
        console.error('Token validation failed:', err);
      }
    }

    validateToken();
  }, []);

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