"use client";

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useDataProvider, useQueryKeyPrefix } from '@/lib/demo/data-provider-context';
import { trackEvent, AnalyticsEvents } from '@/lib/analytics';
import type { CreateResidenceRequest, UpdateResidenceRequest, ResidenceResponse } from '@/lib/api/residences';

// ---------------------------------------------------------------------------
// Query hooks
// ---------------------------------------------------------------------------

export function useResidences() {
  const { residences } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('residences'),
    queryFn: () => residences.getMyResidences(),
    select: (data) => (Array.isArray(data) ? data : []),
  });
}

export function useResidence(id: number) {
  const { residences } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('residences', id),
    queryFn: () => residences.get(id),
    enabled: !!id,
  });
}

// ---------------------------------------------------------------------------
// Mutation hooks
// ---------------------------------------------------------------------------

export function useCreateResidence() {
  const queryClient = useQueryClient();
  const { residences } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useMutation({
    mutationFn: (data: CreateResidenceRequest) =>
      residences.create(data),
    onSuccess: (result: ResidenceResponse) => {
      trackEvent(AnalyticsEvents.RESIDENCE_CREATED, {
        residence_type: result.property_type?.name,
        platform: 'web',
      });
      queryClient.invalidateQueries({ queryKey: qk('residences') });
    },
  });
}

export function useUpdateResidence(id: number) {
  const queryClient = useQueryClient();
  const { residences } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useMutation({
    mutationFn: (data: UpdateResidenceRequest) =>
      residences.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: qk('residences') });
      queryClient.invalidateQueries({ queryKey: qk('residences', id) });
    },
  });
}

export function useDeleteResidence() {
  const queryClient = useQueryClient();
  const { residences } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useMutation({
    mutationFn: (id: number) => residences.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: qk('residences') });
    },
  });
}
