import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';

export interface WalletTxn {
  uuid: string;
  amount_rials: number;
  type: 'credit' | 'debit' | string;
  description?: string | null;
  balance_after: number;
  created_by_name?: string | null;
  payment_method?: string | null;
  reference?: string | null;
  status?: string;
  created_at: number;
}

interface WalletData {
  balance_rials: number;
  recent_transactions: WalletTxn[];
}

export interface WalletTxnInput {
  amount_rials: number;
  description?: string;
  payment_method?: string;
  reference?: string;
}

/**
 * کیف پول بیمار: موجودی + تراکنش‌های اخیر، و mutationهای شارژ (credit) و برداشت (debit).
 * منبع: GET /api/v1/patient/{uuid}/wallet و POST .../wallet/{charge|withdraw}.
 * کلید کوئری: ['patient-wallet', uuid]؛ پس از هر mutation موفق invalidate می‌شود.
 */
export function usePatientWallet(uuid: string | undefined) {
  const qc = useQueryClient();
  const queryKey = ['patient-wallet', uuid];

  const query = useQuery<ApiResponse<WalletData>>({
    queryKey,
    queryFn: () => api.get(`/api/v1/patient/${uuid}/wallet`),
    enabled: !!uuid,
  });

  const invalidate = () => qc.invalidateQueries({ queryKey });

  const charge = useMutation<ApiResponse<unknown>, unknown, WalletTxnInput>({
    mutationFn: (body) => api.post(`/api/v1/patient/${uuid}/wallet/charge`, body),
    onSuccess: invalidate,
  });

  const withdraw = useMutation<ApiResponse<unknown>, unknown, WalletTxnInput>({
    mutationFn: (body) => api.post(`/api/v1/patient/${uuid}/wallet/withdraw`, body),
    onSuccess: invalidate,
  });

  return {
    balanceRials: query.data?.data?.balance_rials ?? 0,
    transactions: query.data?.data?.recent_transactions ?? [],
    isLoading: query.isLoading,
    charge,
    withdraw,
  };
}
