-- JAuth Luau (Roblox) Client Module
local HttpService = game:GetService("HttpService")

local JAuth = {}
JAuth.__index = JAuth

function JAuth.new(name, ownerid, version, url)
    local self = setmetatable({}, JAuth)
    self.name = name
    self.ownerid = ownerid
    self.version = version or "1.0"
    self.url = (url or "https://jauth.site/api/v1"):gsub("/$", "")
    self.sessionid = nil
    return self
end

function JAuth:init()
    local payload = {
        name = self.name,
        ownerid = self.ownerid,
        version = self.version
    }
    local success, response = pcall(function()
        return HttpService:RequestAsync({
            Url = self.url .. "/init",
            Method = "POST",
            Headers = { ["Content-Type"] = "application/json" },
            Body = HttpService:JSONEncode(payload)
        })
    end)

    if success and response.StatusCode == 200 then
        local data = HttpService:JSONDecode(response.Body)
        if data.success then
            self.sessionid = data.sessionid
            return true, data.message
        end
        return false, data.message
    end
    return false, "Network error during initialization"
end

function JAuth:license(player, key)
    local payload = {
        name = self.name,
        ownerid = self.ownerid,
        key = key,
        hwid = "ROBLOX_UID_" .. tostring(player.UserId),
        sessionid = self.sessionid
    }
    local success, response = pcall(function()
        return HttpService:RequestAsync({
            Url = self.url .. "/license",
            Method = "POST",
            Headers = { ["Content-Type"] = "application/json" },
            Body = HttpService:JSONEncode(payload)
        })
    end)

    if success and response and response.Body then
        local ok, data = pcall(function()
            return HttpService:JSONDecode(response.Body)
        end)
        if ok and type(data) == "table" then
            if data.success then
                return true, data.info or data.message
            end
            return false, data.message or "Authentication failed"
        end
    end
    return false, "Authentication request failed"
end

return JAuth
