/**
 * GET /api/accounting/amazon-ads/status
 * Connection + defaults for the Amazon Ads invoice page: is the Ads API
 * configured (client id/secret), connected (refresh token), which profile is
 * selected, the fixed vendor partner, default charge, and whether the local
 * store/PDF cache works.
 */
import { withRefresh } from '../../../utils/amazonAds/routeShared'
import fetchHelper from '../../../utils/fetchHelper'
import getTokenHelper from '../../../utils/getTokenHelper'
import { getAdsConfig, isAdsApiConfigured, isAdsApiConnected } from '../../../utils/amazonAds/adsApi'
import { adsStoreAvailable, getAdsSetting } from '../../../utils/amazonAds/adsStore'
import { inboxTableAvailable, inboxBackendInfo } from '../../../utils/amazonAds/invoiceStore'

export default withRefresh(async (event, authToken = null) => {
  const token = authToken ?? await getTokenHelper(event)
  const cfg = getAdsConfig(event)
  let vendor: any = null
  try {
    const p: any = await fetchHelper(event, `models/c_bpartner/${cfg.vendorBpartnerId}`, 'GET', token, null)
    if (p?.id) vendor = { id: p.id, name: p.Name, value: p.Value, taxId: p.TaxID || null, isVendor: p.IsVendor === true || p.IsVendor === 'Y', lexofficeContact: !!p.lexware_contact_uuid }
  } catch {}
  const config: any = useRuntimeConfig()
  return {
    status: 200,
    configured: isAdsApiConfigured(event),
    connected: isAdsApiConnected(event),
    connectedAt: getAdsSetting('connected_at'),
    profileId: cfg.profileId,
    profileLabel: getAdsSetting('profile_label'),
    region: cfg.region,
    redirectUri: cfg.redirectUri,
    vendorBpartnerId: cfg.vendorBpartnerId,
    vendor,
    defaultChargeId: cfg.defaultChargeId,
    defaultFeeChargeId: cfg.defaultFeeChargeId,
    storeAvailable: adsStoreAvailable(),
    inboxTable: await inboxTableAvailable(event, token).catch(() => false),
    storeBackend: inboxBackendInfo().backend,
    storeError: inboxBackendInfo().error,
    canFreeNumbers: !!(config.pgHost && config.pgDatabase && config.pgUser && config.pgPassword)
  }
})
