import { createContext, useState } from 'react';

export const AuthContext = createContext({
  token: null,
  userId: null,
  role: null,
  username: null,
  login: () => { },
  logout: () => { },
});

export const AuthProvider = ({ children }) => {
  const [token, setToken] = useState(localStorage.getItem('token') || null);
  const [userId, setUserId] = useState(localStorage.getItem('userId') || null);
  const [role, setRole] = useState(localStorage.getItem('role') || null);
  const [username, setUsername] = useState(localStorage.getItem('username') || null);

  const login = (data) => {
    localStorage.setItem('token', data.token);
    localStorage.setItem('userId', data.userId);
    localStorage.setItem('role', data.role);
    localStorage.setItem('username', data.username);
    setToken(data.token);
    setUserId(data.userId);
    setRole(data.role);
    setUsername(data.username);
  };

  const logout = () => {
    localStorage.clear();

    setToken(null);
    setUserId(null);
    setRole(null);
    setUsername(null);
  };

  const value = {
    token,
    userId,
    role,
    username,
    login,
    logout
  };

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