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'
import { createScenarioSchema, type CreateScenarioInput } from '@/lib/api/schemas'
import { isMeaningfulScenario } from '@/lib/services/simulation-service'

export const dynamic = 'force-dynamic'

export const GET = apiRoute({ permission: 'scenarios.read' }, async () =>
  prisma.scenario.findMany({
    orderBy: [{ isBuiltIn: 'desc' }, { name: 'asc' }],
    include: { targetAsset: { select: { code: true } } },
  }),
)

/** Create a custom scenario. */
export const POST = apiRoute<Record<string, string>, CreateScenarioInput>(
  { permission: 'scenarios.create', bodySchema: createScenarioSchema },
  async ({ body, user, request }) => {
    if (!isMeaningfulScenario(body.params)) throw new ApiError(ERROR_CODES.invalidScenario)

    const key = `custom-${Date.now().toString(36)}`
    const scenario = await prisma.scenario.create({
      data: {
        key,
        name: body.name,
        nameAr: body.nameAr ?? body.name,
        description: body.description ?? '',
        descriptionAr: body.descriptionAr ?? body.description ?? '',
        category: body.category,
        icon: 'scenario',
        isBuiltIn: false,
        loadDeltaPct: body.params.loadDeltaPct ?? 0,
        solarDeltaPct: body.params.solarDeltaPct ?? 0,
        windDeltaPct: body.params.windDeltaPct ?? 0,
        tempDeltaC: body.params.tempDeltaC ?? 0,
        assetOutage: body.params.assetOutage ?? false,
        lineOutage: body.params.lineOutage ?? false,
        batteryOutage: body.params.batteryOutage ?? false,
        evSurgeMw: body.params.evSurgeMw ?? 0,
        industrialMw: body.params.industrialMw ?? 0,
        durationMin: body.params.durationMin ?? 120,
        targetRegion: body.params.regionCode ?? null,
        createdById: user.id,
      },
    })

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

    return scenario
  },
)
