#include "adapters/windows/localization/WindowsLocaleProvider.h"

#include <Windows.h>

#include <algorithm>
#include <cctype>
#include <string>

namespace ta::adapters::windows::localization
{
    std::string system_locale_tag() noexcept
    {
        wchar_t locale_buffer[LOCALE_NAME_MAX_LENGTH] = {};
        if (!GetUserDefaultLocaleName(locale_buffer, LOCALE_NAME_MAX_LENGTH))
            return "en";

        const std::wstring wide(locale_buffer);
        if (wide.empty())
            return "en";

        const int bytes = WideCharToMultiByte(
            CP_UTF8, 0, wide.c_str(), static_cast<int>(wide.size()), nullptr, 0, nullptr, nullptr);
        if (bytes <= 0)
            return "en";

        std::string result(static_cast<std::size_t>(bytes), '\0');
        if (!WideCharToMultiByte(
                CP_UTF8, 0, wide.c_str(), static_cast<int>(wide.size()),
                result.data(), bytes, nullptr, nullptr))
        {
            return "en";
        }

        std::transform(result.begin(), result.end(), result.begin(), [](const unsigned char c)
        {
            return static_cast<char>(std::tolower(c));
        });
        return result;
    }
}
