/**
 * GET /api/oauth/amazon-ads/callback?code=&state=
 * Login-with-Amazon redirect target for the Amazon Ads API consent. Exchanges
 * the code for a refresh token (stored server-side in data/amazon-ads.db) and
 * returns to the Ads invoice page. Register this exact URL as "Allowed Return
 * URL" on the LWA security profile (AMAZON_ADS_OAUTH_REDIRECT_URI).
 */
import { exchangeAdsAuthCode } from '../../../utils/amazonAds/adsApi'
import { getAdsSetting, setAdsSetting } from '../../../utils/amazonAds/adsStore'

const PAGE = '/accounting/amazon-ads-invoices'

export default defineEventHandler(async (event) => {
  const q = getQuery(event)
  const code = q.code as string | undefined
  const state = q.state as string | undefined
  if (!code) return sendRedirect(event, `${PAGE}?ads_error=${encodeURIComponent(String(q.error_description || q.error || 'Amazon-Freigabe abgebrochen'))}`, 302)
  const expected = getAdsSetting('oauth_state')
  if (expected && state !== expected) return sendRedirect(event, `${PAGE}?ads_error=${encodeURIComponent('Ungültiger OAuth-Status (state) — bitte erneut verbinden')}`, 302)
  try {
    await exchangeAdsAuthCode(event, code)
    setAdsSetting('oauth_state', null)
    return sendRedirect(event, `${PAGE}?ads_connected=1`, 302)
  } catch (e: any) {
    return sendRedirect(event, `${PAGE}?ads_error=${encodeURIComponent(e?.message || 'Token-Austausch fehlgeschlagen')}`, 302)
  }
})
