local json = require "cjson"
local request = require "luis.request"
local azure = require "luis.v4_0.azure" 
local INTERNAL_SUBSCRIPTION_ID = "05e90651650a4550aaa817ced8449e3d" -- Este valor NO se encuentra en los valores que retorna los datos de los resources.

module(..., package.seeall)

local m_instanceOwner
function SetOwner (instanceOwner)
	m_instanceOwner = instanceOwner
end

local m_defaultAppVersion = "2022-10-01-preview"

local function MakeCompleteURI (uriBaseId, uri, ...)
	uriBaseId = uriBaseId or "WEBAPI"
	return m_instanceOwner:MakeCompleteURI(m_defaultAppVersion, uriBaseId, uri, ...)
end

local function MakePagingParameters (params)
	local api = require "luis"
	return api.MakePagingParameters(params)
end

function AssignAzureAccountsResourceToApp (appId, vcc)
	assert(type(appId) == "string")
	assert(type(vcc) == "string")

	LogInfo("[LUIS_WEBAPI:AssignAzureAccountsResourceToApp] WEBAPI -> Assigning Azure Account to app: '%s', vcc: '%s'.", appId, vcc)

	-- Obtengo la info las Account de Azure que se han almacenado para el VCC
	local vccAzureAccounts, total = azure.LoadVCCAccounts(vcc)
	if total == 0 then
		local err = {reason = "VCC has not assigned Azure Accounts", vcc = vcc}
		LogError("[LUIS_WEBAPI:AssignAzureAccountsResourceToApp] WEBAPI -> VCC %s has not assigned Azure Accounts.", vcc)
		return false, err
	end
	local vccAzureSubscriptionId = next(vccAzureAccounts)
	local vccAzureAccount = vccAzureAccounts[vccAzureSubscriptionId]
	--LogDebug("1 WEBAPI -> vccAzureAccount %s -> %s", vcc, json.encode(vccAzureAccount))

	local data = {
		subscriptionId = INTERNAL_SUBSCRIPTION_ID, -- Este valor NO se encuentra en los valores que retorna los datos de los resources.
		region = vccAzureAccount.Location or "westus",
		keyPath = "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.CognitiveServices/accounts/%s"
	}

	data.keyPath = data.keyPath:format(
		vccAzureAccount.AzureSubscriptionId, -- "dc506e4a-ff4a-4178-9e18-1750b4247451"
		vccAzureAccount.ResourceGroup, -- "inconcert_luis_grp"
		vccAzureAccount.AccountName -- "inconcert_luis"
	)

	local uri = MakeCompleteURI("WEBAPI_APPS", "%s/subscriptions", appId)
	local success, response = request.Post(uri, data)
	if not success then
		LogError("[LUIS_WEBAPI:AssignAzureAccountsResourceToApp] WEBAPI -> Error Assigning  Azure Account Resource to App '%s'. Error: '%s'", appId, json.encode(response))
		return false, response
	end

	response = table.concat(response)
	LogInfo("[LUIS_WEBAPI:AssignAzureAccountsResourceToApp] WEBAPI -> Success Assigned Azure Account Resource to appId '%s'. Response", appId)

	--LogDebug("[LUIS_WEBAPI:AssignAzureAccountsResourceToApp] WEBAPI -> Assigned Azure Account Resource Response: '%s'", json.encode(response))
	return true, response
end

function UnassignAzureAccountsResourceOfApp (appId, vcc)
	assert(type(appId) == "string")
	assert(type(vcc) == "string")

	LogInfo("[LUIS_WEBAPI:UnassignAzureAccountsResourceOfApp] WEBAPI -> Unassigning Azure Account of app: '%s', vcc: '%s'.", appId, vcc)

	-- Obtengo la info las Account de Azure que se han almacenado para el VCC
	local vccAzureAccounts, total = azure.LoadVCCAccounts(vcc)
	if total == 0 then
		local err = {reason = "VCC has not assigned Azure Accounts", vcc = vcc}
		LogError("[LUIS_WEBAPI:UnassignAzureAccountsResourceOfApp] WEBAPI -> VCC %s has not assigned Azure Accounts.", vcc)
		return false, err
	end

	local uri = MakeCompleteURI("WEBAPI_APPS", "%s/subscriptions/%s", appId, INTERNAL_SUBSCRIPTION_ID)
	local success, response = request.Delete(uri)
	if not success then
		LogError("[LUIS_WEBAPI:UnassignAzureAccountsResourceOfApp] WEBAPI -> Error Unassigning Azure Account Resource of App '%s'. Error: '%s'", appId, json.encode(response))
		return false, response
	end

	response = table.concat(response)
	LogInfo("[LUIS_WEBAPI:UnassignAzureAccountsResourceOfApp] WEBAPI -> Success Unassigned Azure Account Resource of appId '%s'. Response", appId)
	--LogDebug("[LUIS_WEBAPI:UnassignAzureAccountsResourceOfApp] WEBAPI -> Unassigned Azure Account Resource Response: '%s'", response)

	return true, response
end
