import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { assetForwardSeries, getAssetDetail } from '@/lib/services/asset-service'

export const dynamic = 'force-dynamic'

/** One asset: live state, prediction, DNA matches and candidate actions. */
export const GET = apiRoute<{ code: string }>(
  { permission: 'assets.read' },
  async ({ params }) => {
    const detail = await getAssetDetail(decodeURIComponent(params.code))
    if (!detail) throw new ApiError(ERROR_CODES.notFound)

    return {
      asset: {
        code: detail.record.code,
        name: detail.record.name,
        nameAr: detail.record.nameAr,
        type: detail.record.assetType.key,
        region: detail.record.region.code,
        capacityMw: detail.record.capacityMw,
        voltageKv: detail.record.voltageKv,
        ratedTempC: detail.record.ratedTempC,
        customersServed: detail.record.customersServed,
      },
      telemetry: detail.live.sample,
      risk: detail.live.risk,
      rulDays: detail.rulDays,
      prediction: {
        probability: detail.prediction.probability,
        confidence: detail.prediction.confidence,
        etaMinutes: detail.prediction.etaMinutes,
        eventType: detail.prediction.eventType,
        breachReason: detail.prediction.breachReason,
        trajectory: assetForwardSeries(detail.prediction),
      },
      dnaMatches: detail.dnaMatches.map((match) => ({
        code: match.pattern.code,
        similarity: match.similarity,
        contributions: match.contributions,
      })),
      actions: detail.actions,
    }
  },
)
