import { logToDb } from "../db/databaseUtil";

export function safeStringify(obj: unknown) {
  const seen = new WeakSet();

  return JSON.stringify(obj, (_key, value) => {
    if (typeof value === "object" && value !== null) {
      if (seen.has(value)) {
        return "[Circular]";
      }
      seen.add(value);
    }

    if (typeof value === "function") {
      return `[Function: ${value.name || "anonymous"}]`;
    }

    return value;
  });
}

export const logger = {
  debug: (message: string, ...args: unknown[]) => {
    if (process.env.NODE_ENV !== "production") {
      // eslint-disable-next-line no-console
      console.debug(message, ...args);
      // const argsString = args.length > 0 ? " - " + safeStringify(args) : "";
      // logToDb(message + argsString);
    }
  },
  log: (message: string, ...args: unknown[]) => {
    if (
      process.env.NODE_ENV !== "production" ||
      process.env.VITE_PLATFORM === "capacitor"
    ) {
      // eslint-disable-next-line no-console
      console.log(message, ...args);
      const argsString = args.length > 0 ? " - " + safeStringify(args) : "";
      logToDb(message + argsString);
    }
  },
  info: (message: string, ...args: unknown[]) => {
    if (
      process.env.NODE_ENV !== "production" ||
      process.env.VITE_PLATFORM === "capacitor" ||
      process.env.VITE_PLATFORM === "electron"
    ) {
      // eslint-disable-next-line no-console
      console.info(message, ...args);
      const argsString = args.length > 0 ? " - " + safeStringify(args) : "";
      logToDb(message + argsString);
    }
  },
  warn: (message: string, ...args: unknown[]) => {
    // eslint-disable-next-line no-console
    console.warn(message, ...args);
    const argsString = args.length > 0 ? " - " + safeStringify(args) : "";
    logToDb(message + argsString);
  },
  error: (message: string, ...args: unknown[]) => {
    // Errors will always be logged
    // eslint-disable-next-line no-console
    console.error(message, ...args);
    const messageString = safeStringify(message);
    const argsString = args.length > 0 ? safeStringify(args) : "";
    logToDb(messageString + argsString);
  },
};

// Add CommonJS export for Electron
if (typeof module !== "undefined" && module.exports) {
  module.exports = { logger };
}

// Add default export for ESM
export default { logger };
