import { Hono } from "hono";
import { validateSaveData } from "@psx/shared";
import type { Store } from "../db/store.js";

/**
 * Cloud save endpoints (GDD §9).
 *
 * Save payloads are validated with the shared schema before they are stored —
 * the client is not trusted, and in co-op the host writes on behalf of the
 * party, which widens the blast radius of a malformed payload.
 */
export function savesRoutes(store: Store) {
  const app = new Hono();

  app.get("/:campaign/:slot", async (context) => {
    const userId = context.req.header("x-user-id");
    if (!userId) return context.json({ error: "missing x-user-id" }, 401);

    const slot = Number(context.req.param("slot"));
    if (!Number.isInteger(slot)) return context.json({ error: "slot must be an integer" }, 400);

    const record = await store.getSave(userId, context.req.param("campaign"), slot);
    return record ? context.json(record) : context.json({ error: "not found" }, 404);
  });

  app.put("/:campaign/:slot", async (context) => {
    const userId = context.req.header("x-user-id");
    if (!userId) return context.json({ error: "missing x-user-id" }, 401);

    const slot = Number(context.req.param("slot"));
    if (!Number.isInteger(slot)) return context.json({ error: "slot must be an integer" }, 400);

    const body = (await context.req.json().catch(() => null)) as { data?: unknown; title?: string } | null;
    const validation = validateSaveData(body?.data);
    if (!validation.ok) return context.json({ error: "invalid save", details: validation.errors }, 422);

    const record = await store.putSave({
      userId,
      slot,
      campaign: context.req.param("campaign"),
      title: body?.title ?? null,
      data: validation.value,
      playtimeSeconds: validation.value.playtimeSeconds,
    });
    return context.json(record, 200);
  });

  app.get("/", async (context) => {
    const userId = context.req.header("x-user-id");
    if (!userId) return context.json({ error: "missing x-user-id" }, 401);
    return context.json(await store.listSaves(userId));
  });

  return app;
}
