import { createContext, useContext, useEffect, useState } from 'react';
import { authApi, clearSession, getToken } from '../api/client';

const AuthContext = createContext(null);

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const token = getToken();
    if (!token) {
      setLoading(false);
      return;
    }
    authApi
      .me()
      .then((data) => setUser(data))
      .catch(() => clearSession())
      .finally(() => setLoading(false));
  }, []);

  const login = async (username, password) => {
    const data = await authApi.login(username, password);
    localStorage.setItem('authToken', data.token);
    localStorage.setItem('usuario', data.username);
    localStorage.setItem('rolId', String(data.rolId ?? ''));
    setUser({
      username: data.username,
      userId: data.userId,
      rolId: data.rolId,
      confirmed: data.confirmed,
    });
    return data;
  };

  const logout = () => {
    clearSession();
    setUser(null);
  };

  return (
    <AuthContext.Provider value={{ user, loading, login, logout, isAuthenticated: !!getToken() && !!user }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  return useContext(AuthContext);
}
