import { useState, useEffect } from 'react';
import type { SteamUser } from '../types';
import { authService } from '../services/api';

export const useAuth = () => {
  const [user, setUser] = useState<SteamUser | null>(null);

  // Check if user is already authenticated on mount
  useEffect(() => {
    const checkAuthStatus = async () => {
      try {
        console.log('Checking auth status...');
        const response = await authService.getCurrentUser();
        console.log('Auth response:', response);
        if (response.user) {
          console.log('User found:', response.user);
          setUser(response.user);
        } else {
          console.log('No user found in response');
        }
      } catch (error) {
        console.error('Error checking auth status:', error);
        // User is not authenticated, which is fine
      }
    };

    checkAuthStatus();
  }, []);

  const handleLogin = () => {
    console.log('Initiating login...');
    const loginUrl = `${import.meta.env.PROD ? '' : 'http://localhost:3001'}/auth/steam`;
    console.log('Login URL:', loginUrl);
    window.location.href = loginUrl;
  };

  const handleLogout = async () => {
    try {
      await authService.logout();
      setUser(null);
    } catch (error) {
      console.error('Logout failed:', error);
    }
  };

  return { user, handleLogin, handleLogout };
};