import { createLogger } from "@lib/log.ts";
import * as cache from "@lib/cache/cache.ts";
import { getTimeCacheKey, parseTimeCacheKey } from "@lib/string.ts";

const log = createLogger("");
log.addEventListener("log", (data) => {
  cache.set(`log:${getTimeCacheKey()}`, JSON.stringify(data.detail), {
    noLog: true,
  });
});

export type Log = {
  scope: string;
  level: number;
  date: Date;
  args: unknown[];
};

export async function getLogs() {
  const d = new Date();
  const year = d.getFullYear();
  const month = d.getMonth().toString();
  const day = d.getDate().toString();

  const keys = await cache.keys(
    `log:${year}:${month}:${day}:*`,
  );

  const logs = await Promise.all(
    keys.map(async (key) => {
      const date = parseTimeCacheKey(key);
      return { ...JSON.parse(await cache.get<string>(key)), date } as Log;
    }),
  );

  return logs.sort((a, b) => a.date.getTime() > b.date.getTime() ? -1 : 1);
}
