import { LogLevel } from '../../types/electron';

type LogMethod = (tag: string, message: string, context?: Record<string, unknown>) => void;

type ConsoleMethod = 'log' | 'info' | 'warn' | 'error';

class Logger {
  private readonly isDevelopment = import.meta.env.DEV;

  private getConsoleMethod(level: LogLevel): ConsoleMethod {
    return level === 'debug' ? 'log' : level;
  }

  private createLogMethod(level: LogLevel): LogMethod {
    return (tag: string, message: string, context?: Record<string, unknown>): void => {
      // Always output to console in development mode
      if (this.isDevelopment) {
        const contextStr = context ? ` | context: ${JSON.stringify(context)}` : '';
        const consoleMethod = this.getConsoleMethod(level);
        console[consoleMethod](`[${tag}] ${message}${contextStr}`);
      }

      // Send to main process via IPC only if electronAPI is available
      this.sendToMainProcess(level, tag, message, context);
    };
  }

  private sendToMainProcess(
    level: LogLevel,
    tag: string,
    message: string,
    context?: Record<string, unknown>
  ): void {
    try {
      if (window.electronAPI?.logEvent) {
        window.electronAPI.logEvent(level, tag, message, context);
      }
    } catch (error) {
      // Fallback to console if IPC fails
      console.error('Failed to send log to main process:', error);
    }
  }

  public readonly debug = this.createLogMethod('debug');
  public readonly info = this.createLogMethod('info');
  public readonly warn = this.createLogMethod('warn');
  public readonly error = this.createLogMethod('error');
}

export const log = new Logger();
export default log; 