/**
 * Authentication hooks: login, logout, current user, password reset, tenant switching.
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiPost, apiGet, setCsrfToken } from './client';
import { useAuthStore } from '@/store/authStore';

export interface LoginPayload {
  email: string;
  password: string;
}

export interface PasswordResetRequestPayload {
  email: string;
}

export interface PasswordResetConfirmPayload {
  token: string;
  password: string;
}

export function useLogin() {
  const { setUser, setError } = useAuthStore();
  return useMutation({
    mutationFn: (payload: LoginPayload) =>
      apiPost('/auth/login', payload),
    onSuccess: (data: any) => {
      setUser(data.user || data);
      setError(null);
      // Store CSRF token for subsequent unsafe requests
      if (data.csrf_token) {
        setCsrfToken(data.csrf_token);
      }
    },
    onError: (error: any) => {
      setError(error.message || 'Login failed');
    },
  });
}

export function useLogout() {
  const { logout } = useAuthStore();
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: () => apiPost('/auth/logout'),
    onSettled: () => {
      logout();
      setCsrfToken(null);
      queryClient.clear();
    },
  });
}

export function useCurrentUser() {
  const { setUser, setAuthenticated } = useAuthStore();
  return useQuery({
    queryKey: ['currentUser'],
    queryFn: async () => {
      const data = await apiGet<any>('/auth/me');
      setUser(data.user || data);
      setAuthenticated(true);
      return data;
    },
    retry: false,
    staleTime: 5 * 60 * 1000,
  });
}

export function usePasswordResetRequest() {
  return useMutation({
    mutationFn: (payload: PasswordResetRequestPayload) =>
      apiPost('/auth/password-reset/request', payload),
  });
}

export function usePasswordResetConfirm() {
  return useMutation({
    mutationFn: (payload: PasswordResetConfirmPayload) =>
      apiPost('/auth/password-reset/confirm', payload),
  });
}

export function useSwitchTenant() {
  const { setTenant } = useAuthStore();
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (tenantId: string) =>
      apiPost('/auth/switch-tenant', { tenant_id: tenantId }),
    onSuccess: (data: any) => {
      setTenant(data.tenant || data);
      queryClient.invalidateQueries();
    },
  });
}
