type ResourceUrl =
  | 'https://teams.optovia.ru'
  | 'https://orders.optovia.ru'
  | 'https://kyc.optovia.ru'
  | 'https://exchange.optovia.ru'

interface TokenCache {
  token: string
  expiresAt: number
}

const tokenCache = new Map<ResourceUrl, TokenCache>()

export const useResourceToken = () => {
  const getToken = async (resource: ResourceUrl): Promise<string> => {
    // Проверяем кеш (с запасом 60 сек)
    const cached = tokenCache.get(resource)
    if (cached && cached.expiresAt > Date.now() + 60000) {
      return cached.token
    }

    // Запрашиваем новый токен через exchange endpoint
    const response = await $fetch<{
      access_token: string
      expires_in: number
    }>('/api/auth/exchange-token', {
      method: 'POST',
      body: { resource }
    })

    // Кешируем
    tokenCache.set(resource, {
      token: response.access_token,
      expiresAt: Date.now() + response.expires_in * 1000
    })

    return response.access_token
  }

  return { getToken }
}
