import { string } from 'alga-js'
import refreshTokenHelper from "../../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"
import fetchHelper from "../../../utils/fetchHelper"
import { resolveMarketplaceId } from "../../../utils/amazonSpApi"
import { marketplaceKeyOf, marketplaceLabel, supportsListings } from "../../../utils/listings/adapters"

// Order sources with a listings adapter (Amazon, Shopify / shopify-new) for the
// SIS page — every active source the caller's role can read, with a marketplace
// key + label so the picker can show an icon per entry.
const handleFunc = async (event: any, authToken: any = null) => {
  const token = authToken ?? await getTokenHelper(event)

  const res: any = await fetchHelper(
    event,
    `models/c_ordersource?$filter=${string.urlEncode('isActive eq true')}&$orderby=${string.urlEncode('Name asc')}`,
    'GET',
    token,
    null
  )

  const records = (res?.records || [])
    .filter((os: any) => supportsListings(os))
    .map((os: any) => ({
      id: os.id,
      name: os.Name || '',
      marketplace: marketplaceKeyOf(os),
      marketplaceName: marketplaceLabel(marketplaceKeyOf(os)),
      orgId: os?.AD_Org_ID?.id ?? null,
      orgName: os?.AD_Org_ID?.identifier || '',
      value: os.Value || '',
      description: os.Description || '',
      marketplaceIdentifier: os?.Marketplace?.identifier || '',
      marketplaceId: resolveMarketplaceId(os?.Marketplace?.identifier, os?.Description),
      amazonMerchantId: os?.amazon_merchant_id || os?.Amazon_Merchant_ID || '',
      hasCreds: marketplaceKeyOf(os) === 'amazon'
        ? !!(os.marketplace_key && os.marketplace_secret && os.marketplace_token)
        : marketplaceKeyOf(os) === 'ebay'
          ? /access_token|refresh_token/.test(String(os.marketplace_token || ''))
          : !!(os.marketplace_url && (os.marketplace_token || (os.marketplace_key && os.marketplace_secret)))
    }))

  return { status: 200, records }
}

export default defineEventHandler(async (event) => {
  let data: any = {}

  try {
    data = await handleFunc(event)
  } catch (err: any) {
    try {
      let authToken: any = await refreshTokenHelper(event)
      data = await handleFunc(event, authToken)
    } catch (error: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})
