import { useReactMutation } from '@/app/hooks/use-react-mutation';
import { useReactQuery } from '@/app/hooks/use-react-query';
import { useReactQueryClient } from '@/app/hooks/use-react-query-client';
import { authClient } from '@/lib/auth-client';

import type { ApiKey } from '../types';

interface CreateApiKeyParams {
  name: string;
  expiresIn?: number;
}

interface CreateApiKeyResult {
  key: string;
  id: string;
}

export function useApiKeys(organizationId: string) {
  return useReactQuery({
    queryKey: ['api-keys', organizationId],
    queryFn: async () => {
      const result = await authClient.apiKey.list();
      if (result.error) {
        throw new Error(result.error.message);
      }
      // authClient.apiKey.list() now returns { apiKeys, total, limit, offset }
      return (result.data?.apiKeys ?? []) as ApiKey[];
    },
  });
}

export function useCreateApiKey(organizationId: string) {
  const queryClient = useReactQueryClient();

  return useReactMutation({
    mutationFn: async ({
      name,
      expiresIn,
    }: CreateApiKeyParams): Promise<CreateApiKeyResult> => {
      const result = await authClient.apiKey.create({
        name,
        expiresIn,
      });

      if (result.error) {
        throw new Error(result.error.message);
      }

      if (!result.data?.key || !result.data?.id) {
        throw new Error('API key creation returned no key/id');
      }

      return {
        key: result.data.key,
        id: result.data.id,
      };
    },
    onSuccess: () => {
      void queryClient.invalidateQueries({
        queryKey: ['api-keys', organizationId],
      });
    },
  });
}

export function useRevokeApiKey(organizationId: string) {
  const queryClient = useReactQueryClient();

  return useReactMutation({
    mutationFn: async (keyId: string) => {
      const result = await authClient.apiKey.delete({
        keyId,
      });

      if (result.error) {
        throw new Error(result.error.message);
      }

      return result.data;
    },
    onSuccess: () => {
      void queryClient.invalidateQueries({
        queryKey: ['api-keys', organizationId],
      });
    },
  });
}
