import { app, BrowserWindow } from 'electron';
import { cleanupLinuxScreenShareAudioRouting } from '../audio/linux-screen-share-routing';
import { initializeDesktopUpdater, shutdownDesktopUpdater } from '../update/desktop-updater';
import { synchronizeAutoStartSetting } from './auto-start';
import { migrateLegacyDesktopBranding } from './desktop-branding-migration';
import { applyLocalApiSettings, stopLocalApiServer } from '../api';
import {
  initializeDatabase,
  destroyDatabase,
  getDataSource
} from '../db/database';
import {
  createWindow,
  getDockIconPath,
  getMainWindow,
  prepareWindowForAppQuit,
  showMainWindow
} from '../window/create-window';
import {
  setupCqrsHandlers,
  setupSystemHandlers,
  setupWindowControlHandlers
} from '../ipc';
import { startIdleMonitor, stopIdleMonitor } from '../idle/idle-monitor';
import {
  attachRendererDiagnosticsHooks,
  ensurePerfDiagIpcRegistered,
  shutdownPerfDiagnostics,
  startPerfDiagnostics
} from '../diagnostics';

function startLocalApiAfterWindowReady(): void {
  setImmediate(() => {
    void applyLocalApiSettings().catch((error: unknown) => {
      console.error('[LocalApi] Failed to apply settings after window startup:', error);
    });
  });
}

export function registerAppLifecycle(): void {
  ensurePerfDiagIpcRegistered();

  app.whenReady().then(async () => {
    const dockIconPath = getDockIconPath();

    if (process.platform === 'darwin' && dockIconPath)
      app.dock?.setIcon(dockIconPath);

    await initializeDatabase();
    setupCqrsHandlers();
    setupWindowControlHandlers();
    setupSystemHandlers();
    await migrateLegacyDesktopBranding();
    await synchronizeAutoStartSetting();
    initializeDesktopUpdater();
    startPerfDiagnostics();
    await createWindow();

    const mainWindow = getMainWindow();

    if (mainWindow) {
      attachRendererDiagnosticsHooks(mainWindow);
    }

    startLocalApiAfterWindowReady();
    startIdleMonitor();

    app.on('activate', () => {
      if (getMainWindow()) {
        void showMainWindow();
        return;
      }

      if (BrowserWindow.getAllWindows().length === 0)
        void createWindow();
    });
  });

  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin')
      app.quit();
  });

  app.on('before-quit', async (event) => {
    prepareWindowForAppQuit();
    await shutdownPerfDiagnostics();

    if (getDataSource()?.isInitialized) {
      event.preventDefault();
      shutdownDesktopUpdater();
      stopIdleMonitor();
      await stopLocalApiServer();
      await cleanupLinuxScreenShareAudioRouting();
      await destroyDatabase();
      app.quit();
    }
  });
}
