import AutoLaunch from 'auto-launch'
import { app } from 'electron'

let autoLauncher: AutoLaunch | null = null

export async function setupAutoLaunch(enabled: boolean): Promise<void> {
  if (!autoLauncher) {
    autoLauncher = new AutoLaunch({
      name: 'Game Marathon Tracker',
      path: app.getPath('exe'),
    })
  }

  try {
    const isEnabled = await autoLauncher.isEnabled()

    if (enabled && !isEnabled) {
      await autoLauncher.enable()
      console.log('Auto-launch enabled')
    } else if (!enabled && isEnabled) {
      await autoLauncher.disable()
      console.log('Auto-launch disabled')
    }
  } catch (error) {
    console.error('Failed to setup auto-launch:', error)
  }
}

export async function isAutoLaunchEnabled(): Promise<boolean> {
  if (!autoLauncher) {
    autoLauncher = new AutoLaunch({
      name: 'Game Marathon Tracker',
      path: app.getPath('exe'),
    })
  }

  try {
    return await autoLauncher.isEnabled()
  } catch {
    return false
  }
}
