/**
 * Bridge between the persisted `assets` row and the pure `AssetProfile` the simulation
 * engine consumes. Kept in one place so the seed script and the runtime build profiles
 * identically — that identity is what makes recorded history and live telemetry agree.
 */

import type { AssetTypeKey } from '../domain/enums'
import type { AssetProfile } from '../engine/telemetry'

/** The shape any asset query must select to be convertible into a profile. */
export interface AssetProfileSource {
  code: string
  regionId?: string
  lat: number
  lon: number
  capacityMw: number
  voltageKv: number
  ratedTempC: number
  coolingType: string
  baselineLoadPct: number
  peakHour: number
  volatility: number
  seed: number
  healthScore: number
  agingFactor: number
  profileKey: string
  installedAt: Date
  lastMaintenanceAt: Date | null
  customersServed: number
  isFlexibleLoad: boolean
  hasBatterySupport: boolean
  status: string
  assetType: { key: string }
  region: { code: string }
}

export function toAssetProfile(asset: AssetProfileSource): AssetProfile {
  return {
    code: asset.code,
    assetTypeKey: asset.assetType.key as AssetTypeKey,
    regionCode: asset.region.code,
    capacityMw: asset.capacityMw,
    voltageKv: asset.voltageKv,
    ratedTempC: asset.ratedTempC,
    coolingType: asset.coolingType,
    baselineLoadPct: asset.baselineLoadPct,
    peakHour: asset.peakHour,
    volatility: asset.volatility,
    seed: asset.seed,
    healthScore: asset.healthScore,
    agingFactor: asset.agingFactor,
    profileKey: asset.profileKey,
    installedAt: asset.installedAt.getTime(),
    lastMaintenanceAt: asset.lastMaintenanceAt ? asset.lastMaintenanceAt.getTime() : null,
    customersServed: asset.customersServed,
    isFlexibleLoad: asset.isFlexibleLoad,
    hasBatterySupport: asset.hasBatterySupport,
    status: asset.status,
  }
}

/** The Prisma `select`/`include` fragment that satisfies `AssetProfileSource`. */
export const ASSET_PROFILE_SELECT = {
  code: true,
  lat: true,
  lon: true,
  capacityMw: true,
  voltageKv: true,
  ratedTempC: true,
  coolingType: true,
  baselineLoadPct: true,
  peakHour: true,
  volatility: true,
  seed: true,
  healthScore: true,
  agingFactor: true,
  profileKey: true,
  installedAt: true,
  lastMaintenanceAt: true,
  customersServed: true,
  isFlexibleLoad: true,
  hasBatterySupport: true,
  status: true,
  assetType: { select: { key: true } },
  region: { select: { code: true } },
} as const
