package com.izouma.nineth.web;

import com.izouma.nineth.service.RedisLock;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;

@RestController
@RequestMapping("/teststock")
@AllArgsConstructor
public class TestStockController {

    private RedisLock                     redisLock;
    private RedisTemplate<String, Object> redisTemplate;

    @PostConstruct
    public void init() {
        redisTemplate.opsForValue().set("teststock", 1000);
    }

    @GetMapping("/setup")
    public void setup() {
        redisTemplate.opsForValue().getAndSet("teststock", 1000);
    }

    @GetMapping("/test")
    public String test() {
        int stock = Math.toIntExact(redisTemplate.opsForValue().decrement("teststock", 1));
        if (stock < 0) {
            redisTemplate.opsForValue().increment("teststock", 1);
            return "库存不足";
        } else {
            return "ok";
        }
    }
}
