import { useState } from 'react';
import type { RegisterInput, RegisterOutput } from '../schemas';

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

// --- USER CODE START ---

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

  async function register(input: RegisterInput): Promise<RegisterOutput> {
    setLoading(true);
    setError(null);
    setSuccess(false);

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

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

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

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

  return { register, loading, error, success };
}

// --- USER CODE END ---
