-- 领券传入的数据格式,对于redis来说,lua是原子性的,有事务的

-- 检验库存信息 这里的key是
local cachePrefix = KEYS[1]
-- 领券id couponUserId
local orderId = KEYS[2]
local activityId = KEYS[3]
local prodCount = tonumber(KEYS[4])
local userId = KEYS[5]
local maxNum = tonumber(KEYS[6])
local receiveNum = 0

-- 用户领券上限
if (redis.call('exists', cachePrefix.."receive:".. activityId.."_"..userId) == "1") then
    -- 用户领券数量
    receiveNum = tonumber(redis.call('get', cachePrefix.."receive:".. activityId.."_"..userId))
end
if maxNum < (receiveNum + 1) then
    return "-2"
end

-- 因为有可能库存从别的地方扣减，这里只做锁定的记录
if prodCount ~= 0 then
    -- 下面通过get获取当前的库存数量
    local stock = tonumber(redis.call('get', cachePrefix.."stock:".. activityId.."_"..activityId))

    if prodCount > stock then
        -- 库存不足返回-1
        return "-1"
    end
    -- 更新剩余库存
    redis.call('set',cachePrefix.."stock:".. activityId.."_"..activityId,tostring(stock - prodCount))
end

-- 保存锁定记录
redis.call('set',cachePrefix.."lock:"..activityId.."_"..userId.."_"..orderId, tostring(prodCount))
-- 更新领券数量
redis.call('set',cachePrefix.."receive:"..activityId.."_"..userId, receiveNum + 1)

return "1"
