'use client';

import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import type { PayoutState } from '@alqove/api-client';

export const PAYOUT_KEYS = {
  list: (
    storeId: string,
    params: { state?: PayoutState; page?: number; per_page?: number },
  ) =>
    [
      'payouts',
      storeId,
      params.state ?? 'all',
      params.page ?? 1,
      params.per_page ?? 20,
    ] as const,
  one: (storeId: string, payoutId: string) =>
    ['payouts', storeId, payoutId] as const,
};

export function useStorePayouts(
  storeId: string | null | undefined,
  params: { state?: PayoutState; page?: number; per_page?: number } = {},
) {
  return useQuery({
    queryKey: storeId ? PAYOUT_KEYS.list(storeId, params) : ['payouts', 'none'],
    queryFn: () => api.payouts.listForStore(storeId!, params),
    enabled: Boolean(storeId),
    staleTime: 30_000,
  });
}

export function useStorePayout(
  storeId: string | null | undefined,
  payoutId: string | null | undefined,
) {
  return useQuery({
    queryKey:
      storeId && payoutId
        ? PAYOUT_KEYS.one(storeId, payoutId)
        : ['payouts', 'none'],
    queryFn: () => api.payouts.getForStore(storeId!, payoutId!),
    enabled: Boolean(storeId && payoutId),
    staleTime: 30_000,
  });
}
