import { prisma } from '@/lib/db'
import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'

export const dynamic = 'force-dynamic'

/**
 * Delete a custom scenario.
 *
 * Built-in scenarios cannot be removed — they are part of the product surface — and the
 * simulations already run against a deleted scenario are kept, so past results stay
 * reproducible.
 */
export const DELETE = apiRoute<{ id: string }>(
  { permission: 'scenarios.delete' },
  async ({ params, user, request }) => {
    const scenario = await prisma.scenario.findFirst({
      where: { OR: [{ id: params.id }, { key: params.id }] },
    })
    if (!scenario) throw new ApiError(ERROR_CODES.notFound)
    if (scenario.isBuiltIn) {
      throw new ApiError(ERROR_CODES.conflict, {
        message: 'Built-in scenarios cannot be deleted.',
      })
    }

    await prisma.scenario.delete({ where: { id: scenario.id } })

    await writeAudit({
      action: AUDIT_ACTIONS.scenarioDeleted,
      entity: 'scenario',
      entityId: scenario.id,
      user,
      request,
      before: { key: scenario.key, name: scenario.name },
    })

    return { deleted: scenario.key }
  },
)
