//go:build windows

package startup

import (
	"errors"
	"os"

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

const runKeyPath = `SOFTWARE\Microsoft\Windows\CurrentVersion\Run`

type registryRunKey struct {
	key registry.Key
}

func (k *registryRunKey) GetString(name string) (string, error) {
	value, _, err := k.key.GetStringValue(name)
	if errors.Is(err, registry.ErrNotExist) {
		return "", ErrValueNotFound
	}
	return value, err
}

func (k *registryRunKey) SetString(name, value string) error {
	return k.key.SetStringValue(name, value)
}

func (k *registryRunKey) Delete(name string) error {
	err := k.key.DeleteValue(name)
	if errors.Is(err, registry.ErrNotExist) {
		return ErrValueNotFound
	}
	return err
}

func NewWindowsController() (*Controller, error) {
	key, _, err := registry.CreateKey(registry.CURRENT_USER, runKeyPath, registry.QUERY_VALUE|registry.SET_VALUE)
	if err != nil {
		return nil, err
	}
	return &Controller{
		Store: &registryRunKey{key: key},
		ExecutablePath: func() (string, error) {
			return os.Executable()
		},
	}, nil
}
