//go:build windows

package platform

import (
	"errors"
	"os"

	"golang.org/x/sys/windows/registry"
)

const (
	// runKeyPath is the per-user autostart key — entries here launch at sign-in
	// without elevation (HKLM would need admin).
	runKeyPath   = `Software\Microsoft\Windows\CurrentVersion\Run`
	runValueName = "Commilitia Drop"
)

// SetLaunchAtLogin adds or removes the per-user Run registry entry that starts
// the app at sign-in. The value is the quoted executable path (so a Program
// Files path with spaces stays one argument) followed by --hidden, so a login
// launch comes up to the tray with no window (see launchedHidden in main).
func SetLaunchAtLogin(enabled bool) error {
	k, _, err := registry.CreateKey(registry.CURRENT_USER, runKeyPath, registry.SET_VALUE)
	if err != nil {
		return err
	}
	defer k.Close()

	if !enabled {
		if err := k.DeleteValue(runValueName); err != nil && !errors.Is(err, registry.ErrNotExist) {
			return err
		}
		return nil
	}

	exe, err := os.Executable()
	if err != nil {
		return err
	}
	return k.SetStringValue(runValueName, `"`+exe+`" --hidden`)
}

// IsLaunchAtLoginEnabled reports whether the Run entry is present.
func IsLaunchAtLoginEnabled() bool {
	k, err := registry.OpenKey(registry.CURRENT_USER, runKeyPath, registry.QUERY_VALUE)
	if err != nil {
		return false
	}
	defer k.Close()
	_, _, err = k.GetStringValue(runValueName)
	return err == nil
}
