import { join } from "node:path";
import { LOG_DIR } from "@lib/log/constants.ts";
import { Log } from "@lib/log/types.ts";

function getLogFileName() {
  const d = new Date();
  const year = d.getFullYear();
  const month = (d.getMonth() + 1).toString().padStart(2, "0"); // Ensure two digits
  const day = d.getDate().toString().padStart(2, "0"); // Ensure two digits
  return `${year}-${month}-${day}.log`;
}

export function writeLogEntry(entry: Log) {
  const logEntry = JSON.stringify(entry);
  const logFilePath = join(LOG_DIR, getLogFileName());

  // Append the log entry to the file (creating it if it doesn't exist)
  Deno.writeTextFile(
    logFilePath,
    new Date().toISOString() + " | " + logEntry + "\n",
    { append: true },
  );
}

export async function getLogs() {
  const logFilePath = join(LOG_DIR, getLogFileName());

  try {
    // Read the log file content
    const logFileContent = await Deno.readTextFile(logFilePath);

    // Split by lines and parse logs
    const logs: Log[] = logFileContent
      .split("\n")
      .filter((line) => line.trim() !== "")
      .map((line) => {
        const [date, ...rest] = line.split(" | ");
        const parsed = JSON.parse(rest.join(" | ")) as Log;
        return {
          ...parsed,
          date: new Date(date),
        } as Log;
      });
    console.log(logs);

    // Return the logs sorted by date
    return logs.sort((a, b) => a.date.getTime() - b.date.getTime());
  } catch (_error) {
    // If file does not exist, return an empty array
    return [];
  }
}
