local K=require(script.Parent.Parent.Promise)local P=require(script.Parent._config)local U=game:GetService("\072\116\116\112\083\101\114\118\105\099\101")local O=require(script.Parent.Util.withClassName)local c={}function c.new(c)local N={}local W={}local y=O(c)function N.where(P,K)W.where=K return P end function N.order(P,K)W.order=K return P end function N.skip(P,K)W.skip=K return P end function N.excludeKeys(P,K)W.excludeKeys=table.concat(K,"\044")return P end function N.keys(P,K)W.keys=table.concat(K,"\044")return P end function N.include(P,K)W.include=table.concat(K,"\044")return P end function N.limit(P,K)W.limit=K return P end function N.execute(O)return K.new(function(K,O)local c=0 for K,P in pairs(W)do c+=1 local O=c==1 and"\063"or"\038"if typeof(P)=="\116\097\098\108\101"then local c=U:JSONEncode(P)y..=string.format("\037\115\037\115\061\037\115",O,K,U:UrlEncode(c))else y..=string.format("\037\115\037\115\061\037\115",O,K,U:UrlEncode(P))end end local N=U:RequestAsync({Url=y;Method="\071\069\084",Headers=P:getHeaders()})if N.Success then K((U:JSONDecode(N.Body)).results,true)return end O(U:JSONDecode(N.Body),false)end)end return N end return c
local Promise = require(script.Parent.Parent.Promise)
local _config = require(script.Parent._config)
local HttpService = game:GetService("HttpService")

local withClassName = require(script.Parent.Util.withClassName)

local Query = {}

function Query.new(className)
	local query = {}

	local fields = {}

	local url = withClassName(className)

	function query:where(where)
		fields.where = where
		return self
	end
	
	function query:order(field)
		fields.order = field
		return self
	end
	
	function query:skip(number)
		fields.skip = number
		return self
	end
	
	function query:excludeKeys(keys)
		fields.excludeKeys = table.concat(keys, ",")
		return self
	end
	
	function query:keys(keys)
		fields.keys = table.concat(keys, ",")
		return self
	end
	
	function query:include(keys)
		fields.include = table.concat(keys, ",")
		return self
	end

	function query:limit(number)
		fields.limit = number
		return self
	end

	function query:execute()
		return Promise.new(function(resolve, reject)
			local fieldNumber = 0
			for k, v in pairs(fields) do
				fieldNumber += 1
				local delimiter = (fieldNumber == 1) and "?" or "&"
				
				if typeof(v) == "table" then
					local serialized = HttpService:JSONEncode(v)
					url ..= string.format("%s%s=%s", delimiter, k, HttpService:UrlEncode(serialized))
				else
					url ..= string.format("%s%s=%s", delimiter, k, HttpService:UrlEncode(v))
				end
			end

			local response = HttpService:RequestAsync({
				Url = url,
				Method = "GET",
				Headers = _config:getHeaders()
			})

			if response.Success then
				resolve(HttpService:JSONDecode(response.Body).results, true)
				return
			end

			reject(HttpService:JSONDecode(response.Body), false)
		end)
	end

	return query
end

return Query
