import { useState } from 'react';
import type { LoginInput, LoginOutput } from '../schemas';

// --- ASA GENERATED START ---
// React hook for auth/login slice.
// --- ASA GENERATED END ---

// --- USER CODE START ---

export function useLogin() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function login(input: LoginInput): Promise<LoginOutput> {
    setLoading(true);
    setError(null);

    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(input),
      });

      const data: LoginOutput = await res.json();

      if (!data.success) {
        setError(data.error);
      }

      return data;
    } catch {
      const output: LoginOutput = { success: false, error: 'Network error. Please try again.' };
      setError(output.error);
      return output;
    } finally {
      setLoading(false);
    }
  }

  return { login, loading, error };
}

// --- USER CODE END ---
