'use client'

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { apiClient } from '../client'
import { useAuthReady } from '../use-auth-ready'
import type {
  ApiToken,
  ApiTokenCreated,
  CreateApiTokenPayload,
} from '../types'

export function useApiTokens() {
  const { ready, authenticated } = useAuthReady()

  return useQuery({
    queryKey: ['api-tokens'],
    queryFn: async () => {
      const res = await apiClient.get<ApiToken[] | { tokens: ApiToken[] }>(
        '/mail/api-tokens'
      )
      return Array.isArray(res) ? res : (res.tokens ?? [])
    },
    staleTime: 30_000,
    enabled: ready && authenticated,
    retry: 1,
  })
}

export function useCreateApiToken() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (payload: CreateApiTokenPayload) =>
      apiClient.post<ApiTokenCreated>('/mail/api-tokens', payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['api-tokens'] })
    },
  })
}

export function useRevokeApiToken() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (tokenId: string) =>
      apiClient.delete(`/mail/api-tokens/${tokenId}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['api-tokens'] })
    },
  })
}
