import {
  isSettlementMarketplace,
  resetSettlementExports,
  settlementExportLogAvailable
} from '../../../utils/settlementExportLog'
import { userNameOf } from '../../../utils/amazonAds/routeShared'

// Clears the per-period lexoffice CSV export state (the period-level counterpart
// of the C_Order marker reset in lexoffice-csv-export.post.ts).
//   POST { marketplace, orderSourceId, periodIds: string[], scope?: 'all'|'positions'|'payout' }
//   → { status, periods: { [periodId]: PeriodExportRecord } } (missing key = cleared)
export default defineEventHandler(async (event) => {
  await getTokenHelper(event)
  const body = await readBody(event)
  const marketplace = String(body?.marketplace || '')
  const orderSourceId = Number(body?.orderSourceId || 0)
  const periodIds = [...new Set((Array.isArray(body?.periodIds) ? body.periodIds : []).map((id: any) => String(id || '')).filter(Boolean))] as string[]
  const scope = ['all', 'positions', 'payout'].includes(String(body?.scope || '')) ? String(body.scope) as any : 'all'
  if (!isSettlementMarketplace(marketplace) || !orderSourceId || !periodIds.length) {
    return { status: 400, message: 'marketplace, orderSourceId and periodIds are required' }
  }
  if (!settlementExportLogAvailable()) {
    return { status: 503, message: 'Export-Protokoll nicht verfügbar (data/settlement-exports.db konnte nicht geöffnet werden)' }
  }
  const periods = resetSettlementExports({ marketplace, orderSourceId, periodIds, scope, user: userNameOf(event) })
  return {
    status: 200,
    message: `Export-Markierung für ${periodIds.length} Zeitraum/Zeiträume zurückgesetzt`,
    periods
  }
})
