import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { demoBaseTimestamp } from '@/lib/demo/config'
import { assessVoltageStability } from '@/lib/services/physics-grid-service'

export const dynamic = 'force-dynamic'

/**
 * Voltage stability over the areas that solved.
 *
 * The index follows the weakest bus rather than the average — a network is as stable as
 * its worst bus — and the response carries the share of the model the assessment covers,
 * so an area that did not solve reads as unassessed rather than as sound.
 */
export const GET = apiRoute({ permission: 'twin.read', limit: 60 }, async ({ searchParams }) => {
  const report = await assessVoltageStability({
    twinCode: searchParams.get('twin') ?? undefined,
    ts: searchParams.get('clock') === 'demo' ? demoBaseTimestamp() : undefined,
  })
  if (!report) throw new ApiError(ERROR_CODES.notFound)
  return report
})
