import { Router, type Request, type Response } from "express";
import { db, worldEvents } from "@workspace/db";
import { desc } from "drizzle-orm";
import { getWorldState } from "../lib/world-state.js";
import { makeLogger } from "../lib/logger.js";

const logger = makeLogger("world");
const router = Router();

router.get("/world/state", async (_req: Request, res: Response) => {
  try {
    const state = getWorldState();
    const recent = await db
      .select()
      .from(worldEvents)
      .orderBy(desc(worldEvents.createdAt))
      .limit(20);

    res.json({
      ...state,
      recentEvents: recent.reverse(),
    });
  } catch (err) {
    logger.error("GET /api/world/state failed", { error: String(err) });
    res.status(500).json({ error: "world_state_error" });
  }
});

export default router;
