import { Hono } from "hono";
import { useDrizzle } from "@/lib/db.js";
import { systemSetting } from "@/db/schema.js";
import type { HonoEnv } from "@/types/hono.ts";
import {
  SETTINGS_KEY_OCPP16J,
  getOcpp16jSettings,
  sanitizeHeartbeatInterval,
  type SettingsPayload,
} from "@/lib/system-settings.js";

const app = new Hono<HonoEnv>();

app.get("/", async (c) => {
  const payload: SettingsPayload = {
    ocpp16j: await getOcpp16jSettings(),
  };

  return c.json(payload);
});

app.put("/", async (c) => {
  const currentUser = c.get("user");
  if (currentUser?.role !== "admin") {
    return c.json({ error: "Forbidden" }, 403);
  }

  let body: Partial<SettingsPayload>;
  try {
    body = await c.req.json<Partial<SettingsPayload>>();
  } catch {
    return c.json({ error: "Invalid JSON" }, 400);
  }

  if (!body.ocpp16j) {
    return c.json({ error: "Missing ocpp16j settings" }, 400);
  }

  const heartbeatInterval = sanitizeHeartbeatInterval(body.ocpp16j.heartbeatInterval);

  const db = useDrizzle();
  await db
    .insert(systemSetting)
    .values({
      key: SETTINGS_KEY_OCPP16J,
      value: { heartbeatInterval },
    })
    .onConflictDoUpdate({
      target: systemSetting.key,
      set: {
        value: { heartbeatInterval },
        updatedAt: new Date(),
      },
    });

  const payload: SettingsPayload = {
    ocpp16j: {
      heartbeatInterval,
    },
  };

  return c.json(payload);
});

export default app;
