import { eq } from 'drizzle-orm'
import dayjs from 'dayjs'
import { useDrizzle } from '@/lib/db.js'
import { chargePoint } from '@/db/schema.js'
import type {
  HeartbeatRequest,
  HeartbeatResponse,
  OcppConnectionContext,
} from '../types.ts'

export async function handleHeartbeat(
  _payload: HeartbeatRequest,
  ctx: OcppConnectionContext,
): Promise<HeartbeatResponse> {
  const db = useDrizzle()

  await db
    .update(chargePoint)
    .set({
      lastHeartbeatAt: dayjs().toDate(),
      transportStatus: 'online',
      updatedAt: dayjs().toDate(),
    })
    .where(eq(chargePoint.chargePointIdentifier, ctx.chargePointIdentifier))

  return {
    currentTime: dayjs().toISOString(),
  }
}
