--[[
	SklopGuard v2 - license check for Sklop assets
	A server-only ModuleScript. Put it inside your Sklop asset and require it from the asset's main
	server Script so the asset can't run without it. It confirms this experience's owner still holds a
	valid Sklop license; if the license is revoked, it calls your onRevoked and the asset turns off.

	HOW TO USE (in the asset's main server Script):
		local Guard = require(script.Parent.SklopGuard)
		local Shop   -- your real module

		Guard.Protect({
			product = "shop-kit",          -- the Sklop product slug (shown on its store page URL)
			onRevoked = function(reason)
				if Shop then Shop:Disable() end  -- turn off your asset however you like
			end,
		})

	HOW IT BEHAVES
	* Revoked stays revoked: once Sklop confirms a revocation, this experience remembers it in its own
	  DataStore. The asset stays off after restarts, even if Sklop can't be reached or HTTP requests
	  are turned off afterwards. Only Sklop restoring the license turns it back on (after a restart).
	* HTTP requests are required in live servers (Game Settings > Security > Allow HTTP Requests).
	  If they're off, the asset stays off and says why. In Studio, the check is skipped while testing.
	* If Sklop or Roblox is briefly unreachable, a licensed asset keeps running (it re-checks later).
	* Keep this module in your asset. If you remove it, the require above errors and the asset
	  won't start: that's intended.
	* Runs on the server only. Calling it from a LocalScript does nothing.

	(c) Sklop (sklop.me). Licensed with the asset; don't redistribute or remove this check.
]]

local DataStoreService = game:GetService("DataStoreService")
local HttpService = game:GetService("HttpService")
local RunService = game:GetService("RunService")

local SITE_URL = "https://sklop.me"
local CHECK_INTERVAL = 900 -- re-check every 15 minutes
local STORE_NAME = "SklopGuard"

local Guard = {}

-- Returns the decoded reply, or nil plus a reason ("http_disabled" or "unreachable").
local function verify(productSlug)
	local ok, response = pcall(function()
		return HttpService:RequestAsync({
			Url = SITE_URL .. "/api/roblox/verify",
			Method = "POST",
			Headers = { ["Content-Type"] = "application/json" },
			Body = HttpService:JSONEncode({
				productSlug = productSlug,
				creatorType = game.CreatorType.Name, -- "User" or "Group"
				creatorId = tostring(game.CreatorId),
			}),
		})
	end)
	if not ok then
		local message = string.lower(tostring(response))
		if string.find(message, "not enabled", 1, true) or string.find(message, "http requests", 1, true) then
			return nil, "http_disabled"
		end
		return nil, "unreachable"
	end
	if not response.Success then
		return nil, "unreachable"
	end
	local decoded, data = pcall(function()
		return HttpService:JSONDecode(response.Body)
	end)
	if not decoded or typeof(data) ~= "table" then
		return nil, "unreachable"
	end
	return data
end

-- The experience's own memory of a revocation, so turning HTTP off later can't bring the asset back.
local function openStore()
	local ok, store = pcall(function()
		return DataStoreService:GetDataStore(STORE_NAME)
	end)
	if ok then
		return store
	end
	return nil
end

local function rememberedRevoked(store, productSlug)
	if not store then
		return false
	end
	local ok, value = pcall(function()
		return store:GetAsync("revoked/" .. productSlug)
	end)
	return ok and typeof(value) == "table" and value.revoked == true
end

local function remember(store, productSlug, revoked)
	if not store then
		return
	end
	pcall(function()
		if revoked then
			store:SetAsync("revoked/" .. productSlug, { revoked = true, at = os.time() })
		else
			store:RemoveAsync("revoked/" .. productSlug)
		end
	end)
end

-- Protect(config): config.product (slug, required), config.onRevoked (function(reason)),
-- config.interval (seconds, optional). Returns a handle with :IsRevoked() and :Check().
-- reason is "license_revoked" or "http_disabled".
function Guard.Protect(config)
	assert(typeof(config) == "table" and typeof(config.product) == "string", "SklopGuard.Protect needs { product = \"your-slug\" }")
	if RunService:IsClient() then
		warn("[SklopGuard] must run on the server; ignoring.")
		return {
			IsRevoked = function()
				return false
			end,
			Check = function() end,
		}
	end

	local product = config.product
	local onRevoked = config.onRevoked
	local interval = tonumber(config.interval) or CHECK_INTERVAL
	local inStudio = RunService:IsStudio()
	local store = openStore()
	local revoked = false

	local function turnOff(reason)
		if revoked then
			return
		end
		revoked = true
		if reason == "http_disabled" then
			warn(("[SklopGuard] \"%s\" is off: turn on Game Settings > Security > Allow HTTP Requests so its license can be checked."):format(product))
		else
			warn(("[SklopGuard] \"%s\" is off: the Sklop license for this experience's owner was revoked. Contact Sklop support if this is a mistake."):format(product))
		end
		if typeof(onRevoked) == "function" then
			task.spawn(onRevoked, reason)
		end
	end

	local function check()
		local data, problem = verify(product)
		if not data then
			-- HTTP turned off in a live server: stay off. Briefly unreachable: keep running.
			if problem == "http_disabled" and not inStudio then
				turnOff("http_disabled")
			end
			return
		end
		if data.revoked == true then
			remember(store, product, true)
			turnOff("license_revoked")
		elseif data.resolved == true and data.licensed == true and rememberedRevoked(store, product) then
			-- Sklop restored the license: forget the revocation (takes effect on the next server start).
			remember(store, product, false)
		end
	end

	task.spawn(function()
		if rememberedRevoked(store, product) then
			turnOff("license_revoked")
		end
		check()
		while true do
			task.wait(interval)
			check()
		end
	end)

	return {
		IsRevoked = function()
			return revoked
		end,
		Check = check,
	}
end

return Guard
