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 { CreateChildSchema, UpdateChildSchema } from "@haushaltsApp/shared/schemas/children.schema";
import {
  getChildren,
  getChildById,
  createChild,
  updateChild,
  deleteChild,
} from "../services/children.service";

type Variables = AuthVariables & TenantVariables;

export const childrenRoutes = new Hono<{ Variables: Variables }>();

childrenRoutes.use("/*", authMiddleware, requireAuth, tenantMiddleware, requireHousehold);

// GET /api/children — list all children for household
childrenRoutes.get("/", async (c) => {
  const householdId = c.get("householdId") as string;
  const data = await getChildren(householdId);
  return c.json({ children: data });
});

// GET /api/children/:id
childrenRoutes.get("/:id", async (c) => {
  const householdId = c.get("householdId") as string;
  const { id } = c.req.param();
  const child = await getChildById(id, householdId);
  if (!child) return c.json({ error: "Not found" }, 404);
  return c.json({ child });
});

// POST /api/children
childrenRoutes.post("/", zValidator("json", CreateChildSchema), async (c) => {
  const householdId = c.get("householdId") as string;
  const input = c.req.valid("json");
  const child = await createChild(householdId, input);
  return c.json({ child }, 201);
});

// PATCH /api/children/:id
childrenRoutes.patch("/:id", zValidator("json", UpdateChildSchema), async (c) => {
  const householdId = c.get("householdId") as string;
  const { id } = c.req.param();
  const input = c.req.valid("json");
  const child = await updateChild(id, householdId, input);
  if (!child) return c.json({ error: "Not found" }, 404);
  return c.json({ child });
});

// DELETE /api/children/:id
childrenRoutes.delete("/:id", async (c) => {
  const householdId = c.get("householdId") as string;
  const { id } = c.req.param();
  const child = await deleteChild(id, householdId);
  if (!child) return c.json({ error: "Not found" }, 404);
  return c.json({ child });
});
