import { eq } from "drizzle-orm";
import { systemSetting } from "@/db/schema.js";
import { useDrizzle } from "@/lib/db.js";

export const SETTINGS_KEY_OCPP16J = "ocpp16j";
const DEFAULT_HEARTBEAT_INTERVAL = 60;
const MIN_HEARTBEAT_INTERVAL = 10;
const MAX_HEARTBEAT_INTERVAL = 86400;

export type Ocpp16jSettings = {
  heartbeatInterval: number;
};

export type SettingsPayload = {
  ocpp16j: Ocpp16jSettings;
};

export function sanitizeHeartbeatInterval(raw: unknown): number {
  if (typeof raw !== "number" || !Number.isFinite(raw)) {
    return DEFAULT_HEARTBEAT_INTERVAL;
  }
  const n = Math.round(raw);
  if (n < MIN_HEARTBEAT_INTERVAL) return MIN_HEARTBEAT_INTERVAL;
  if (n > MAX_HEARTBEAT_INTERVAL) return MAX_HEARTBEAT_INTERVAL;
  return n;
}

export function getDefaultHeartbeatInterval(): number {
  return DEFAULT_HEARTBEAT_INTERVAL;
}

export async function getOcpp16jSettings(): Promise<Ocpp16jSettings> {
  const db = useDrizzle();
  const [ocpp16jRow] = await db
    .select()
    .from(systemSetting)
    .where(eq(systemSetting.key, SETTINGS_KEY_OCPP16J))
    .limit(1);

  const ocpp16jRaw = (ocpp16jRow?.value ?? {}) as Record<string, unknown>;

  return {
    heartbeatInterval: sanitizeHeartbeatInterval(ocpp16jRaw.heartbeatInterval),
  };
}
