import { Router, type IRouter } from "express";
import { eq } from "drizzle-orm";
import { db } from "@workspace/db";
import { appSettingsTable } from "@workspace/db";
import { requireAdmin } from "../middlewares/auth";
import { UpdateAppSettingsBody } from "@workspace/api-zod";

const router: IRouter = Router();

async function ensureSettingsRow() {
  await db
    .insert(appSettingsTable)
    .values({ id: 1 })
    .onConflictDoNothing({ target: appSettingsTable.id });
}

async function readSettings() {
  await ensureSettingsRow();
  const [row] = await db.select().from(appSettingsTable).where(eq(appSettingsTable.id, 1));
  return row;
}

router.get("/settings", async (_req, res): Promise<void> => {
  res.json(await readSettings());
});

router.patch("/settings", requireAdmin, async (req, res): Promise<void> => {
  const parsed = UpdateAppSettingsBody.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: parsed.error.message });
    return;
  }
  await ensureSettingsRow();
  const [updated] = await db
    .update(appSettingsTable)
    .set(parsed.data)
    .where(eq(appSettingsTable.id, 1))
    .returning();
  res.json(updated);
});

export default router;
