/**
 * DELETE /api/surveillance/shipment-recording/cleanup?token=xxx
 *
 * Removes the cached recording file once the user has finished watching
 * (modal closed or video ended). Idempotent — succeeds even if the file
 * was already swept by the TTL fallback.
 */

import { unlink } from 'node:fs/promises'
import { join } from 'node:path'
import { tmpdir } from 'node:os'

const CACHE_DIR_NAME = 'logship-surveillance'

function cacheDir(): string {
  return join(tmpdir(), CACHE_DIR_NAME)
}

function isSafeToken(token: string): boolean {
  return /^[a-f0-9]{32}$/.test(token)
}

export default defineEventHandler(async (event) => {
  const query = getQuery(event)
  const token = String(query.token || '')
  if (!isSafeToken(token)) {
    throw createError({ statusCode: 400, statusMessage: 'Invalid token.' })
  }

  const filePath = join(cacheDir(), `${token}.mp4`)
  await unlink(filePath).catch(() => null)
  return { ok: true }
})
