'use client';

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import type { AuthUser, LoginInput } from '@vihar/shared';
import { api, ApiError } from './api';

export function useMe() {
  return useQuery({
    queryKey: ['auth', 'me'],
    queryFn: () => api.get<AuthUser>('/api/auth/me'),
    retry: false,
    staleTime: 60 * 1000,
  });
}

export function useLogin() {
  const router = useRouter();
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (input: LoginInput) => api.post<{ user: AuthUser }>('/api/auth/login', input),
    onSuccess: ({ user }) => {
      qc.setQueryData(['auth', 'me'], user);
      // Route by role
      if (user.isCaptain && user.isVolunteer) router.push('/role');
      else if (user.isCaptain) router.push('/captain');
      else router.push('/volunteer');
    },
  });
}

export function useLogout() {
  const router = useRouter();
  const qc = useQueryClient();
  return useMutation({
    mutationFn: () => api.post<{ ok: true }>('/api/auth/logout'),
    onSuccess: () => {
      qc.clear();
      router.push('/login');
    },
  });
}

export function useRequireAuth(): { user: AuthUser | undefined; isLoading: boolean } {
  const { data, error, isLoading } = useMe();
  const router = useRouter();
  if (error instanceof ApiError && error.status === 401) {
    if (typeof window !== 'undefined') router.push('/login');
  }
  return { user: data, isLoading };
}
