export * from './client.js'
export * from './api.js'
export * from './oauth1.js'
export * from './search-criteria.js'
export * from './types.js'

import type { z } from 'zod'
import type { magentoEnv, Logger } from '@znet/shared'
import { MagentoClient } from './client.js'
import { MagentoApi } from './api.js'

/** Build a MagentoApi from validated env. */
export function magentoFromEnv(env: z.infer<typeof magentoEnv>, logger?: Logger, timeoutMs?: number): MagentoApi {
  // OAuth 1.0a needs all three extra values; a partial set would silently fall back to Bearer.
  const oauthParts = [env.MAGENTO_CONSUMER_KEY, env.MAGENTO_CONSUMER_SECRET, env.MAGENTO_ACCESS_TOKEN_SECRET]
  const given = oauthParts.filter(Boolean).length
  if (given > 0 && given < oauthParts.length) {
    throw new Error('Magento OAuth 1.0a needs MAGENTO_CONSUMER_KEY, MAGENTO_CONSUMER_SECRET and MAGENTO_ACCESS_TOKEN_SECRET together (plus MAGENTO_ACCESS_TOKEN)')
  }
  logger?.info({ auth: given ? 'oauth1' : 'bearer' }, 'magento auth mode')
  return new MagentoApi(
    new MagentoClient({
      baseUrl: env.MAGENTO_BASE_URL,
      accessToken: env.MAGENTO_ACCESS_TOKEN,
      oauth1: {
        consumerKey: env.MAGENTO_CONSUMER_KEY,
        consumerSecret: env.MAGENTO_CONSUMER_SECRET,
        accessTokenSecret: env.MAGENTO_ACCESS_TOKEN_SECRET,
      },
      ...(logger ? { logger } : {}),
      ...(timeoutMs ? { timeoutMs } : {}),
    }),
  )
}
