import { useQuery } from '@tanstack/react-query';

import { AuthService } from '@/client/services/AuthService';

const CAPTCHA_W_MIN = 80;
const CAPTCHA_W_MAX = 400;
const CAPTCHA_H_MIN = 30;
const CAPTCHA_H_MAX = 200;

function clamp(value: number, min: number, max: number): number {
  return Math.max(min, Math.min(max, value));
}

export function useCaptcha({
  w = 200,
  h = 80,
  dark = false,
  rsa = true,
}: {
  w?: number;
  h?: number;
  dark?: boolean;
  rsa?: boolean;
} = {}) {
  const safeW = clamp(w, CAPTCHA_W_MIN, CAPTCHA_W_MAX);
  const safeH = clamp(h, CAPTCHA_H_MIN, CAPTCHA_H_MAX);

  return useQuery({
    queryKey: ['auth', 'captcha', { w: safeW, h: safeH, dark, rsa }],
    queryFn: () =>
      AuthService.authGetCaptcha({ w: safeW, h: safeH, dark, rsa }).then((r) => r.data),
    staleTime: 0,
    gcTime: 0,
  });
}
