import { createContext, useState } from 'react';
import { clearApiCacheForCurrentUser } from '../api/offlineCache';

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 clearAuthStorage = () => {
    clearApiCacheForCurrentUser();
    localStorage.removeItem("token");
    localStorage.removeItem("userId");
    localStorage.removeItem("role");
    localStorage.removeItem("username");
  };

  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 = () => {
    clearAuthStorage();

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

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

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