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

export const dynamic = 'force-dynamic'

/**
 * Generation plus discharge against load, losses and charging.
 *
 * The residual is reported rather than absorbed into a slack term: a balance that does not
 * close is the finding, and hiding it would throw away the only evidence that something is
 * unaccounted for.
 */
export const GET = apiRoute({ permission: 'twin.read', limit: 60 }, async ({ searchParams }) => {
  const report = await computeEnergyBalance({
    twinCode: searchParams.get('twin') ?? undefined,
    ts: searchParams.get('clock') === 'demo' ? demoBaseTimestamp() : undefined,
    mode: searchParams.get('mode') === 'fast' ? 'fast' : 'ac',
  })
  if (!report) throw new ApiError(ERROR_CODES.notFound)
  return report
})
