'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient, ApiClientError } from '@/lib/apiClient';
import type {
  ApiKey,
  ApiKeyCreateResponse,
  ApiKeyCreateApiResponse,
  ApiKeyRevokeResponse,
} from './types';

const API_KEYS_QUERY_KEY = ['api-keys'];

interface ApiKeysListApiResponse {
  data: ApiKey[];
  meta: {
    total: number;
  };
}

export type ApiKeyErrorCode = 'PRO_FEATURE_REQUIRED' | 'API_KEY_LIMIT_REACHED' | 'API_KEY_NOT_FOUND';

export interface ApiKeyError {
  status: number;
  code: ApiKeyErrorCode;
  message: string;
}

export function useApiKeys() {
  const queryClient = useQueryClient();

  const {
    data: keysData,
    isLoading,
    error,
  } = useQuery<ApiKeysListApiResponse, ApiClientError>({
    queryKey: API_KEYS_QUERY_KEY,
    queryFn: async () => {
      return apiClient.get<ApiKeysListApiResponse>('/api/v1/api-keys');
    },
    retry: (failureCount, err) => {
      if (err.status === 403 || err.status === 429) return false;
      return failureCount < 2;
    },
  });

  const keys = keysData?.data ?? [];
  const total = keysData?.meta?.total ?? 0;

  const generateKeyMutation = useMutation<ApiKeyCreateResponse, ApiClientError, string | undefined>({
    mutationFn: async (name?: string): Promise<ApiKeyCreateResponse> => {
      const response = await apiClient.post<ApiKeyCreateApiResponse>('/api/v1/api-keys', {
        name: name || 'API Key',
      });
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: API_KEYS_QUERY_KEY });
    },
  });

  const revokeKeyMutation = useMutation<ApiKeyRevokeResponse, ApiClientError, string>({
    mutationFn: async (keyId: string): Promise<ApiKeyRevokeResponse> => {
      return apiClient.delete<ApiKeyRevokeResponse>(`/api/v1/api-keys/${keyId}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: API_KEYS_QUERY_KEY });
    },
  });

  const generateKey = async (name?: string) => {
    return generateKeyMutation.mutateAsync(name);
  };

  const revokeKey = async (keyId: string) => {
    return revokeKeyMutation.mutateAsync(keyId);
  };

  const parseError = (error: ApiClientError | null): ApiKeyError | null => {
    if (!error) return null;
    
    const status = error.status || 500;
    const code = error.code as ApiKeyErrorCode | string;
    const message = error.message;
    
    if (status === 403 && code === 'PRO_FEATURE_REQUIRED') {
      return { status: 403, code: 'PRO_FEATURE_REQUIRED', message: message || 'Pro feature required' };
    }
    if (status === 429 && code === 'API_KEY_LIMIT_REACHED') {
      return { status: 429, code: 'API_KEY_LIMIT_REACHED', message: message || 'Maximum API keys reached' };
    }
    if (status === 404 && code === 'API_KEY_NOT_FOUND') {
      return { status: 404, code: 'API_KEY_NOT_FOUND', message: message || 'API key not found' };
    }
    
    // For non-matching errors, return with the actual code but cast appropriately for type safety
    return { status, code: code as ApiKeyErrorCode, message };
  };

  return {
    keys,
    total,
    isLoading,
    error,
    errorDetails: parseError(error),
    isGenerating: generateKeyMutation.isPending,
    isRevoking: revokeKeyMutation.isPending,
    generateKey,
    revokeKey,
    generateError: generateKeyMutation.error,
    revokeError: revokeKeyMutation.error,
    parseGenerateError: () => parseError(generateKeyMutation.error),
    parseRevokeError: () => parseError(revokeKeyMutation.error),
  };
}
