/**
 * POST /api/print-agent/backup  (Bearer agent token)
 * Body: { tarBase64 }  — nightly tar.gz of the device's /etc/cups (queues + PPDs), ≤ 5 MB.
 * Stored per agent under data/print-agent-backups/; a replacement box restores it via GET.
 */
import { existsSync, mkdirSync } from 'node:fs'
import { writeFile } from 'node:fs/promises'
import path from 'node:path'
import { requireAgent } from '../../utils/printAgentAuth'

const MAX_BYTES = 5 * 1024 * 1024

export const backupPath = (agentId: number) => path.join(process.cwd(), 'data', 'print-agent-backups', `agent-${agentId}.tar.gz`)

export default defineEventHandler(async (event) => {
  const agent = requireAgent(event)
  const body = await readBody(event).catch(() => ({})) || {}
  const b64 = String(body.tarBase64 || '')
  if (!b64) throw createError({ statusCode: 400, statusMessage: 'tarBase64 is required' })
  const buf = Buffer.from(b64, 'base64')
  if (!buf.length || buf.length > MAX_BYTES) throw createError({ statusCode: 413, statusMessage: 'backup too large (max 5 MB)' })
  const file = backupPath(agent.id)
  const dir = path.dirname(file)
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
  await writeFile(file, buf)
  return { ok: true, bytes: buf.length, storedAt: new Date().toISOString() }
})
