#include "AutoStart.h"

namespace {

const wchar_t* RUN_KEY = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";

// 获取默认 appName（exe 文件名，不含 .exe 后缀）
std::wstring GetDefaultAppName() {
    wchar_t path[MAX_PATH];
    GetModuleFileNameW(nullptr, path, MAX_PATH);
    wchar_t* name = wcsrchr(path, L'\\');
    if (!name) name = path; else ++name;
    std::wstring result(name);
    // 去掉 .exe 后缀
    size_t dot = result.rfind(L'.');
    if (dot != std::wstring::npos) result = result.substr(0, dot);
    return result;
}

// 获取完整 exe 路径
std::wstring GetExePath() {
    wchar_t path[MAX_PATH];
    GetModuleFileNameW(nullptr, path, MAX_PATH);
    return path;
}

} // anonymous namespace

namespace AutoStart {

bool IsEnabled(const wchar_t* appName) {
    std::wstring name = appName ? std::wstring(appName) : GetDefaultAppName();

    HKEY hKey = nullptr;
    if (RegOpenKeyExW(HKEY_CURRENT_USER, RUN_KEY, 0, KEY_READ, &hKey) != ERROR_SUCCESS) {
        return false;
    }

    DWORD type = 0;
    LSTATUS result = RegQueryValueExW(hKey, name.c_str(), nullptr, &type, nullptr, nullptr);
    RegCloseKey(hKey);

    return (result == ERROR_SUCCESS && type == REG_SZ);
}

bool Enable(const wchar_t* appName, const wchar_t* exePath) {
    std::wstring name = appName ? std::wstring(appName) : GetDefaultAppName();
    std::wstring path = exePath ? std::wstring(exePath) : GetExePath();

    HKEY hKey = nullptr;
    if (RegOpenKeyExW(HKEY_CURRENT_USER, RUN_KEY, 0, KEY_WRITE, &hKey) != ERROR_SUCCESS) {
        return false;
    }

    DWORD dataSize = static_cast<DWORD>((path.size() + 1) * sizeof(wchar_t));
    LSTATUS result = RegSetValueExW(hKey, name.c_str(), 0, REG_SZ,
        reinterpret_cast<const BYTE*>(path.c_str()), dataSize);
    RegCloseKey(hKey);

    return result == ERROR_SUCCESS;
}

bool Disable(const wchar_t* appName) {
    std::wstring name = appName ? std::wstring(appName) : GetDefaultAppName();

    HKEY hKey = nullptr;
    if (RegOpenKeyExW(HKEY_CURRENT_USER, RUN_KEY, 0, KEY_WRITE, &hKey) != ERROR_SUCCESS) {
        return false;
    }

    LSTATUS result = RegDeleteValueW(hKey, name.c_str());
    RegCloseKey(hKey);

    return result == ERROR_SUCCESS;
}

} // namespace AutoStart
