import refreshTokenHelper from "../../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"
import fetchHelper from "../../../utils/fetchHelper"
import { getEbayContext, listPayouts, parseAmount } from "../../../utils/ebayFinancesApi"

// List the available eBay payouts (lump-sum bank deposits) for an order source.
// Each payout = one settlement period; these populate the period dropdown on the
// eBay settlement-browser page.
const handleFunc = async (event: any, authToken: any = null) => {
  const token = authToken ?? await getTokenHelper(event)
  const query = getQuery(event)
  const orderSourceId = query.orderSourceId
  const payoutDateFrom = query.payoutDateFrom ? String(query.payoutDateFrom) : undefined
  const payoutDateTo = query.payoutDateTo ? String(query.payoutDateTo) : undefined

  if (!orderSourceId) {
    return { status: 400, message: 'orderSourceId is required' }
  }

  const orderSource: any = await fetchHelper(event, `models/c_ordersource/${orderSourceId}`, 'GET', token, null)
  if (!orderSource) {
    return { status: 404, message: 'Order source not found' }
  }

  const marketplaceIdentifier = String(orderSource?.Marketplace?.identifier || '').toLowerCase()
  const isEbay = marketplaceIdentifier === 'ebay' || String(orderSource?.Marketplace?.id) === '5' || String(orderSource?.marketplace) === '5'
  if (!isEbay) {
    return { status: 400, message: `Order source "${orderSource?.Name || orderSourceId}" is not an eBay marketplace` }
  }

  if (!orderSource?.marketplace_token) {
    return { status: 400, message: 'eBay account is not connected for this order source (no stored token).' }
  }

  const ctx = await getEbayContext(orderSource)
  const { payouts, total } = await listPayouts(ctx, { payoutDateFrom, payoutDateTo })

  const mapped = payouts.map((p: any) => ({
    payoutId: p.payoutId,
    payoutStatus: p.payoutStatus || '',
    payoutStatusDescription: p.payoutStatusDescription || '',
    payoutDate: p.payoutDate || '',
    amount: parseAmount(p.amount),
    currency: p.amount?.currency || 'EUR',
    transactionCount: p.transactionCount ?? null,
    instrument: p.payoutInstrument?.[0]?.accountLastFourDigits
      ? `••${p.payoutInstrument[0].accountLastFourDigits}`
      : (p.payoutInstrument?.[0]?.instrumentType || '')
  }))

  return {
    status: 200,
    orderSourceId: Number(orderSourceId),
    environment: ctx.environment,
    payouts: mapped,
    total
  }
}

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

  try {
    data = await handleFunc(event)
  } catch (err: any) {
    // eBay API errors (e.g. token expired, missing scope) carry a status —
    // surface them verbatim rather than treating them as an iDempiere auth failure.
    if (err?.status && err?.message) {
      return { status: err.status, message: err.message, ebay: err.ebay }
    }
    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
})
