import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import { authMiddleware, requireAuth, type AuthVariables } from "../middleware/auth.middleware";
import { tenantMiddleware, requireHousehold, type TenantVariables } from "../middleware/tenant.middleware";
import { UpdateHouseholdSettingsSchema } from "@haushaltsApp/shared/schemas/household-settings.schema";
import {
  getOrCreateHouseholdSettings,
  updateHouseholdSettings,
} from "../services/household-settings.service";

type Variables = AuthVariables & TenantVariables;

export const householdSettingsRoutes = new Hono<{ Variables: Variables }>();
householdSettingsRoutes.use("/*", authMiddleware, requireAuth, tenantMiddleware, requireHousehold);

householdSettingsRoutes.get("/", async (c) => {
  const householdId = c.get("householdId") as string;
  const settings = await getOrCreateHouseholdSettings(householdId);
  return c.json({ settings });
});

householdSettingsRoutes.patch("/", zValidator("json", UpdateHouseholdSettingsSchema), async (c) => {
  const householdId = c.get("householdId") as string;
  const input = c.req.valid("json");
  const settings = await updateHouseholdSettings(householdId, input);
  return c.json({ settings });
});
