'use client';

import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useRouter, useSearchParams } from 'next/navigation';
import { apiClient } from '@/lib/apiClient';
import type { RegisterRequest, RegisterResponse } from './types';
import type { LoginResponse } from '../login/types';

interface ApiError {
  message: string;
  error?: string;
}

export function useRegister() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const redirect = searchParams.get('redirect') || '/dashboard';
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (data: RegisterRequest) => {
      await apiClient.post<RegisterResponse>('/api/v1/auth/register', data);

      const loginResponse = await apiClient.post<{ data: LoginResponse; meta: Record<string, unknown> }>(
        '/api/v1/auth/login',
        { email: data.email, password: data.password }
      );
      return loginResponse.data;
    },
    onSuccess: (data) => {
      queryClient.clear();
      localStorage.setItem('token', data.access_token);
      localStorage.setItem('refresh_token', data.refresh_token);
      router.push(redirect);
    },
    onError: (error: ApiError) => {
      console.error('[useRegister] Registration failed:', error.message);
    },
  });
}
