import type { Context } from "hono";
import type { Kysely } from "kysely";
import type { DB } from "kysely-codegen";
import type {
  ChatbotAdminLogTable,
} from "@/internal/datastore/chatbot.types";

type DBWithAdminLog = DB & {
  chatbot_admin_log: ChatbotAdminLogTable;
};

export const getChatbotAdminHistoryHandler = async (c: Context) => {
  const db = c.get("datastore") as Kysely<DBWithAdminLog>;

  const q = c.req.query();
  const limit = Math.min(Number.parseInt(q.limit ?? "50", 10) || 50, 200);

  const history = await db
    .selectFrom("chatbot_admin_log")
    .selectAll()
    .orderBy("performed_at", "desc")
    .limit(limit)
    .execute();

  return c.json({
    total_logs: history.length,
    history,
  });
};
