// ServiceInstaller.cpp - Modernized implementation
#include "ServiceInstaller.h"
#include <windows.h>
#include <iostream>

void InstallService(const std::wstring& serviceName,
    const std::wstring& displayName,
    DWORD startType,
    const std::wstring& dependencies,
    const std::wstring& account,
    const std::wstring& password)
{
    wchar_t szPath[MAX_PATH];
    if (!GetModuleFileName(nullptr, szPath, MAX_PATH))
    {
        std::wcerr << L"GetModuleFileName failed, error: " << GetLastError() << std::endl;
        return;
    }

    SC_HANDLE schSCManager = OpenSCManager(nullptr, nullptr, SC_MANAGER_CREATE_SERVICE);
    if (!schSCManager)
    {
        std::wcerr << L"OpenSCManager failed, error: " << GetLastError() << std::endl;
        return;
    }

    SC_HANDLE schService = CreateService(
        schSCManager,
        serviceName.c_str(),
        displayName.c_str(),
        SERVICE_ALL_ACCESS,
        SERVICE_WIN32_OWN_PROCESS,
        startType,
        SERVICE_ERROR_NORMAL,
        szPath,
        nullptr,
        nullptr,
        dependencies.empty() ? nullptr : dependencies.c_str(),
        account.empty() ? nullptr : account.c_str(),
        password.empty() ? nullptr : password.c_str()
    );

    if (!schService)
    {
        std::wcerr << L"CreateService failed, error: " << GetLastError() << std::endl;
    }
    else
    {
        std::wcout << L"Service installed successfully." << std::endl;

        if (!StartService(schService, 0, nullptr))
        {
            DWORD err = GetLastError();
            if (err == ERROR_SERVICE_ALREADY_RUNNING)
            {
                std::wcout << L"Service is already running." << std::endl;
            }
            else
            {
                std::wcerr << L"Failed to start service. Error: " << err << std::endl;
            }
        }
        else
        {
            std::wcout << L"Service started successfully." << std::endl;
        }

        CloseServiceHandle(schService);
    }

    CloseServiceHandle(schSCManager);
}

void UninstallService(const std::wstring& serviceName)
{
    SC_HANDLE schSCManager = OpenSCManager(nullptr, nullptr, SC_MANAGER_CONNECT);
    if (!schSCManager)
    {
        std::wcerr << L"OpenSCManager failed, error: " << GetLastError() << std::endl;
        return;
    }

    SC_HANDLE schService = OpenService(schSCManager, serviceName.c_str(), DELETE);
    if (!schService)
    {
        std::wcerr << L"OpenService failed, error: " << GetLastError() << std::endl;
        CloseServiceHandle(schSCManager);
        return;
    }

    if (!DeleteService(schService))
    {
        std::wcerr << L"DeleteService failed, error: " << GetLastError() << std::endl;
    }
    else
    {
        std::wcout << L"Service uninstalled successfully." << std::endl;
    }

    CloseServiceHandle(schService);
    CloseServiceHandle(schSCManager);
}
