-- Autogenerated with DRAKON Editor 1.32
require('strict').on()

local cap_secret = "6LcMXBATAAAAAG6Cji7AQZqFzVigSXdy_dWdOCNq"

local table = table
local string = string
local pairs = pairs
local ipairs = ipairs
local io = io
local pcall = pcall
local xpcall = xpcall
local debug = debug
local tostring = tostring
local clock = require("clock")
local log = require("log")
local digest = require("digest")
local fiber = require("fiber")
local json = require("json")
local fio = require("fio")
local log = require("log")
local os = os
local error = error
local print = print

local utf8 = require("lua-utf8")



local utils = require("utils")
local trans = require("trans")
local mail = require("mail")
local ej = require("ej")
local price_cfg = price_cfg

local global_cfg = global_cfg

local WARNING_BEFORE = utils.days_to_secs(40)

local db = require(global_cfg.db)


setfenv(1, {}) 

function create_coupon(code, product_id, max_users, tag, user_id)
    -- item 422
    local data = {
    	when_created = os.time(),
    	code = code,
    	product_id = product_id,
    	max_users = max_users,
    	tag = tag,
    	user_id = user_id
    }
    -- item 423
    db.coupon_insert(
    	code,
    	data
    )
    -- item 424
    ej.info(
    	"generate coupon",
    	{code=code, user_id=user_id}
    )
end

function create_coupons(count, product_id, max_users, tag, user_id)
    -- item 400
    local i
    local coupons = {}
    -- item 411
    if (max_users < 1) or (max_users > 5000) then
        -- item 415
        error("wrong number of users: "
         .. tostring(max_users))
    else
        -- item 404
        if (count < 1) or (count > 100) then
            -- item 407
            error("wrong number of coupons: "
             .. tostring(count))
        else
            -- item 4020001
            i = 1
            while true do
                -- item 4020002
                if i <= count then
                    
                else
                    break
                end
                -- item 410
                local code = utils.random_string()
                -- item 416
                code = code:sub(1, 16):upper()
                -- item 408
                create_coupon(
                	code,
                	product_id,
                	max_users,
                	tag,
                	user_id
                )
                -- item 409
                table.insert(
                	coupons,
                	code
                )
                -- item 4020003
                i = i + 1
            end
        end
    end
    -- item 401
    return coupons
end

function create_license(user_id, product_id, expiry, limits, trans_id, agreement_id, tag)
    -- item 314
    local now = os.time()
    -- item 312
    local data = {
    	user_id = user_id,
    	product_id = product_id,
    	expiry = expiry,
    	limits = limits,
    	trans_id = trans_id,
    	agreement_id = agreement_id,
    	tag = tag,
    
    	when_created = now,
    	when_updated = now,
    	active = true
    }
    -- item 313
    return db.license_insert(data)
end

function create_transaction(user_id, type, data)
    -- item 461
    local tdata = utils.copy(data)
    -- item 459
    tdata.when_created = os.time()
    tdata.when_updated = tdata.when_created
    tdata.user_id = user_id
    tdata.type = type
    -- item 463
    local id
    while true do
        -- item 464
        id = utils.random_string()
        id = id:sub(1, 10)
        -- item 465
        local old = db.transaction_get(id)
        -- item 466
        if old then
            
        else
            break
        end
    end
    -- item 458
    db.transaction_insert(
    	id,
    	user_id,
    	tdata
    )
    -- item 460
    return id
end

function delete_license(id)
    -- item 392
    if id then
        -- item 544
        local old = db.license_get(id)
        -- item 391
        db.license_delete(id)
        -- item 540
        return old
    else
        -- item 541
        return nil
    end
end

function delete_user_transactions(user_id)
    -- item 535
    local all = db.transaction_get_by_user(user_id)
    for _, tran in ipairs(all) do
        -- item 538
        local id = tran[1]
        db.transaction_delete(id)
    end
end

function get_coupon(code)
    -- item 438
    if code then
        -- item 430
        local data = db.coupon_get(code)
        -- item 431
        if (data) and (not (data.redeemed_by)) then
            -- item 435
            return data
        else
            -- item 434
            return nil
        end
    else
        -- item 434
        return nil
    end
end

function get_license(license_id)
    -- item 320
    local data = get_raw_license(license_id)
    -- item 328
    if (data) and (data.active) then
        -- item 324
        local now = os.time()
        -- item 325
        if now > data.expiry then
            -- item 327
            return nil
        else
            -- item 326
            return data
        end
    else
        -- item 327
        return nil
    end
end

function get_raw_license(id)
    -- item 546
    local expiry = os.time() +
       3600 * 24 * 365 * 20
    -- item 548
    local product = price_cfg.products.basic
    -- item 547
    local limits = {
    	max_diagrams = product.max_diagrams,
    	max_spaces = product.max_spaces,
    	max_users = product.max_users
    }
    -- item 545
    local data = {
    	user_id = nil,
    	product_id = "basic",
    	expiry = expiry,
    	limits = limits,
    	trans_id = nil,
    	agreement_id = nil,
    	tag = nil,
    
    	when_created = nil,
    	when_updated = nil,
    	active = true
    }
    -- item 382
    return data
end

function get_transaction(id)
    -- item 473
    return db.transaction_get(id)
end

function get_user_transactions(user_id)
    -- item 542
    local all = db.transaction_get_by_user(user_id)
    -- item 508
    local result = {}
    for _, tran in ipairs(all) do
        -- item 512
        local id = tran[1]
        local transaction = get_transaction(id)
        -- item 514
        if (transaction.completed) and (transaction.status == "success") then
            -- item 513
            table.insert(result, transaction)
        end
    end
    -- item 524
    local by_when_created = function(left, right)
    	return left.when_created < right.when_created
    end
    -- item 525
    table.sort(
    	result,
    	by_when_created
    )
    -- item 509
    return result
end

function should_show_banner(expiry)
    -- item 485
    local now = os.time()
    -- item 484
    local left = expiry - now
    local show_banner = (left < WARNING_BEFORE)
    -- item 486
    return show_banner
end

function update_coupon(id, fields)
    -- item 444
    local coupon = get_coupon(id)
    -- item 449
    if coupon then
        for key, value in pairs(fields) do
            -- item 447
            coupon[key] = value
        end
        -- item 452
        coupon.when_updated = os.time()
        -- item 448
        db.coupon_update(
        	id,
        	coupon
        )
    end
end

function update_license(id, fields)
    -- item 334
    local license = get_raw_license(id)
    -- item 338
    if license then
        for key, value in pairs(fields) do
            -- item 337
            license[key] = value
        end
        -- item 342
        license.when_updated = os.time()
        -- item 341
        db.license_update(
        	id,
        	license
        )
    end
end

function update_transaction(id, fields)
    -- item 492
    local transaction = get_transaction(id)
    -- item 496
    if transaction then
        for key, value in pairs(fields) do
            -- item 495
            transaction[key] = value
        end
        -- item 499
        transaction.when_updated = os.time()
        -- item 543
        db.transaction_update(
        	transaction.id,
        	transaction.user_id,
        	transaction
        )
    end
end


return {
	create_license = create_license,
	get_license = get_license,
	create_transaction = create_transaction,
	get_transaction = get_transaction,
	create_coupon = create_coupon,
	create_coupons = create_coupons,
	get_coupon = get_coupon,
	update_license = update_license,
	update_coupon = update_coupon,
	get_raw_license = get_raw_license,
	should_show_banner = should_show_banner,
	update_transaction = update_transaction,
	get_user_transactions = get_user_transactions,
	delete_user_transactions = delete_user_transactions,
	delete_license = delete_license
}
