import { prisma } from '@/lib/db'
import { apiRoute, paginated, pagination } from '@/lib/api/handler'
import { getGridSnapshot } from '@/lib/services/grid-service'

export const dynamic = 'force-dynamic'

/**
 * Asset list with live risk.
 *
 * Paginated at the database rather than in the client, because the fleet grows without
 * bound while a page of results does not (§50).
 */
export const GET = apiRoute({ permission: 'assets.read' }, async ({ searchParams }) => {
  const { page, pageSize, skip, take } = pagination(searchParams, 50)
  const regionCode = searchParams.get('region')
  const typeKey = searchParams.get('type')

  const where = {
    ...(regionCode ? { region: { code: regionCode } } : {}),
    ...(typeKey ? { assetType: { key: typeKey } } : {}),
  }

  const [records, total, snapshot] = await Promise.all([
    prisma.asset.findMany({
      where,
      skip,
      take,
      orderBy: { code: 'asc' },
      select: {
        code: true,
        name: true,
        nameAr: true,
        capacityMw: true,
        voltageKv: true,
        healthScore: true,
        status: true,
        criticality: true,
        assetType: { select: { key: true } },
        region: { select: { code: true, name: true, nameAr: true } },
      },
    }),
    prisma.asset.count({ where }),
    getGridSnapshot(),
  ])

  const liveByCode = new Map(snapshot.assets.map((entry) => [entry.profile.code, entry]))

  const items = records.map((record) => {
    const live = liveByCode.get(record.code)
    return {
      ...record,
      loadPct: live?.sample.loadPct ?? null,
      tempC: live?.sample.tempC ?? null,
      riskScore: live?.risk.score ?? null,
      state: live?.state ?? null,
      dnaSimilarity: live?.dnaSimilarity ?? null,
    }
  })

  return paginated(items, total, page, pageSize)
})
