/**
 * TanStack Query hooks for the /v1/tenants/{id}/telegram/bots/*
 * endpoints.
 *
 * The hooks are feature-scoped: callers (list, create-dialog,
 * detail-page) pull these and don't talk to fetchWithAuth
 * directly. That way the cache is shared across views and the
 * query keys are predictable.
 *
 * Cache key strategy: ['telegram-bots', 'list', tenantId, params]
 * for the list, ['telegram-bots', 'detail', tenantId, botId] for
 * the detail. tenantId is part of the key (not just the URL) so
 * the list cache for tenant A doesn't leak when the user
 * navigates to tenant B.
 */

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { ApiError, apiGet, apiSend } from '@/lib/api';
import type {
  CreateTelegramBotInput,
  ListTelegramBotsResponse,
  RotateTelegramBotTokenInput,
  TelegramBot,
  UpdateTelegramBotInput,
} from './types';

export interface ListTelegramBotsParams {
  q?: string;
  status?: string;
  limit?: number;
  offset?: number;
}

const KEYS = {
  list: (tenantId: string | undefined, params: ListTelegramBotsParams) =>
    ['telegram-bots', 'list', tenantId, params] as const,
  detail: (tenantId: string | undefined, botId: string | undefined) =>
    ['telegram-bots', 'detail', tenantId, botId] as const,
};

function buildListQuery(tenantId: string, params: ListTelegramBotsParams): string {
  const u = new URLSearchParams();
  if (params.q) u.set('q', params.q);
  if (params.status) u.set('status', params.status);
  if (params.limit) u.set('limit', String(params.limit));
  if (params.offset) u.set('offset', String(params.offset));
  const s = u.toString();
  return s
    ? `/v1/tenants/${tenantId}/telegram/bots?${s}`
    : `/v1/tenants/${tenantId}/telegram/bots`;
}

export function useTelegramBotsList(tenantId: string | undefined, params: ListTelegramBotsParams) {
  return useQuery({
    queryKey: KEYS.list(tenantId, params),
    queryFn: () =>
      apiGet<ListTelegramBotsResponse>(buildListQuery(tenantId as string, params)),
    enabled: Boolean(tenantId),
    staleTime: 15_000,
  });
}

export function useTelegramBot(tenantId: string | undefined, botId: string | undefined) {
  return useQuery({
    queryKey: KEYS.detail(tenantId, botId),
    queryFn: () => apiGet<TelegramBot>(`/v1/tenants/${tenantId}/telegram/bots/${botId}`),
    enabled: Boolean(tenantId) && Boolean(botId),
  });
}

export function useCreateTelegramBot(tenantId: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (input: CreateTelegramBotInput) =>
      apiSend<TelegramBot>('POST', `/v1/tenants/${tenantId}/telegram/bots`, input),
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: ['telegram-bots', 'list', tenantId] });
    },
  });
}

export function useUpdateTelegramBot(tenantId: string, botId: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (input: UpdateTelegramBotInput) =>
      apiSend<TelegramBot>('PATCH', `/v1/tenants/${tenantId}/telegram/bots/${botId}`, input),
    onSuccess: (bot) => {
      qc.setQueryData(KEYS.detail(tenantId, botId), bot);
      void qc.invalidateQueries({ queryKey: ['telegram-bots', 'list', tenantId] });
    },
  });
}

export function useSetTelegramBotStatus(tenantId: string, botId: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (status: 'active' | 'paused') =>
      apiSend<TelegramBot>('POST', `/v1/tenants/${tenantId}/telegram/bots/${botId}/status`, {
        status,
      }),
    onSuccess: (bot) => {
      qc.setQueryData(KEYS.detail(tenantId, botId), bot);
      void qc.invalidateQueries({ queryKey: ['telegram-bots', 'list', tenantId] });
    },
  });
}

export function useRotateTelegramBotToken(tenantId: string, botId: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (input: RotateTelegramBotTokenInput) =>
      apiSend<TelegramBot>(
        'POST',
        `/v1/tenants/${tenantId}/telegram/bots/${botId}/rotate-token`,
        input,
      ),
    onSuccess: (bot) => {
      qc.setQueryData(KEYS.detail(tenantId, botId), bot);
      void qc.invalidateQueries({ queryKey: ['telegram-bots', 'list', tenantId] });
    },
  });
}

export function getErrorMessage(err: unknown): string {
  if (err instanceof ApiError) {
    const body = err.body as { error?: string; message?: string } | null;
    return body?.message ?? body?.error ?? err.message;
  }
  if (err instanceof Error) return err.message;
  return 'Unknown error';
}
