using Microsoft.Win32;

namespace PersonalToolBox.Helpers;

/// <summary>
/// 开机自启动管理，通过写入 Windows 注册表 Run 键实现
/// </summary>
public static class AutoStartHelper
{
    private const string RunKeyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
    private const string AppName = "PersonalToolBox";

    /// <summary>
    /// 检查当前是否已设置开机自启动
    /// </summary>
    public static bool IsAutoStartEnabled()
    {
        try
        {
            using var key = Registry.CurrentUser.OpenSubKey(RunKeyPath);
            return key?.GetValue(AppName) != null;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 设置或取消开机自启动
    /// </summary>
    public static void SetAutoStart(bool enable)
    {
        try
        {
            using var key = Registry.CurrentUser.OpenSubKey(RunKeyPath, writable: true);
            if (key == null) return;

            if (enable)
            {
                var exePath = Environment.ProcessPath;
                if (exePath != null)
                    key.SetValue(AppName, $"\"{exePath}\" -autostart");
            }
            else
            {
                key.DeleteValue(AppName, throwOnMissingValue: false);
            }
        }
        catch
        {
            // 注册表操作失败时静默忽略（可能是权限不足）
        }
    }
}
