'use client';

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

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

  return useMutation<LoginResponse, ApiClientError, LoginRequest>({
    mutationFn: async (credentials: LoginRequest) => {
      const response = await apiClient.post<{ data: LoginResponse; meta: Record<string, unknown> }>(
        '/api/v1/auth/login',
        credentials
      );
      return response.data;
    },
    onSuccess: (data) => {
      queryClient.clear();
      localStorage.setItem('token', data.access_token);
      localStorage.setItem('refresh_token', data.refresh_token);
      router.push(redirect);
    },
  });
}
