/**
 * POST /api/settings/carrier-rates/import  (staff only)
 * Body: { fixture: 'dhl-2025-07', dryRun: boolean, sections?: string[] (service codes) }
 * dryRun → { status, plan } (diff only, nothing written)
 * apply  → { status, plan: summary, result: { created, updated, failed[] } }
 *
 * ⚠ The dev server's .env points at the PROD iDempiere — a non-dry run writes prod.
 */
import { gateFromEvent } from '../../../utils/chatAccess'
import { applyImport, loadFixture, planImport } from '../../../utils/shipping/carrierRateImport'

const summarize = (plan: any) => ({ ...plan, create: plan.create.slice(0, 50), update: plan.update.slice(0, 50), orphans: plan.orphans.slice(0, 100), totals: { create: plan.create.length, update: plan.update.length, unchanged: plan.unchanged, orphans: plan.orphans.length, skipped: plan.skipped } })

export default defineEventHandler(async (event) => {
  const { token } = await gateFromEvent(event, { requireChat: false })
  const body: any = await readBody(event).catch(() => ({}))
  const fixture = await loadFixture(String(body?.fixture || ''))
  if (!fixture) return { status: 404, message: 'Fixture not found' }
  const sections: string[] | undefined = Array.isArray(body?.sections) && body.sections.length ? body.sections.map(String) : undefined
  try {
    const plan = await planImport(event, token, fixture, sections)
    if (body?.dryRun !== false) return { status: 200, dryRun: true, plan: summarize(plan) }
    const result = await applyImport(event, token, fixture, plan)
    return { status: result.failed.length ? 207 : 200, dryRun: false, plan: summarize(plan), result }
  } catch (err: any) {
    const status = Number(err?.statusCode ?? err?.status ?? err?.response?.status) || 500
    return { status, message: err?.statusMessage || err?.data?.detail || err?.data?.title || err?.message || 'Import failed' }
  }
})
