package com.jeesharp.business.modules.mall.controller;

import com.jeesharp.business.modules.mall.application.MallSeckillSessionApplicationService;
import com.jeesharp.business.modules.mall.application.MallSeckillSkuApplicationService;
import com.jeesharp.business.modules.mall.entity.MallSeckillSession;
import com.jeesharp.business.modules.mall.entity.MallSeckillSku;
import com.jeesharp.framework.pojo.AjaxResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 秒杀移动端 Controller
 */
@RestController
@RequestMapping(value = "${jeesharp.web.adminPath}/mall/seckill/v1")
@Tag(name = "秒杀")
@AllArgsConstructor
public class MallSeckillMobileController {

    private final MallSeckillSessionApplicationService sessionApplicationService;
    private final MallSeckillSkuApplicationService skuApplicationService;

    @Operation(summary = "获取秒杀场次列表")
    @PostMapping(value = "sessions")
    public AjaxResult<List<MallSeckillSession>> getSessions() {
        List<MallSeckillSession> sessions = sessionApplicationService.getActiveSessions();
        return AjaxResult.okData(sessions);
    }

    @Operation(summary = "获取场次秒杀商品")
    @PostMapping(value = "session/skus")
    public AjaxResult<List<MallSeckillSku>> getSessionSkus(@RequestParam("sessionId") String sessionId) {
        List<MallSeckillSku> skus = skuApplicationService.getSessionSkus(sessionId);
        return AjaxResult.okData(skus);
    }

    @Operation(summary = "秒杀下单")
    @PostMapping(value = "order")
    public AjaxResult<Void> seckillOrder(@RequestParam("sessionId") String sessionId,
                                  @RequestParam("skuId") String skuId,
                                  @RequestParam("memberId") String memberId,
                                  @RequestParam("quantity") Integer quantity) {
        // 检查秒杀库存
        if (!skuApplicationService.hasSeckillStock(skuId, quantity)) {
            return AjaxResult.failMsg("秒杀商品库存不足");
        }

        // 扣减秒杀库存
        if (!skuApplicationService.deductSeckillStock(skuId, quantity)) {
            return AjaxResult.failMsg("秒杀失败，请重试");
        }

        // 这里应该调用订单创建逻辑
        // 暂时返回成功，后续需要集成订单创建
        return AjaxResult.ok("秒杀成功，请尽快支付");
    }
}