package com.liquidnet.service.goblin.controller;

import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.goblin.dto.vo.GoblinSqbPerfGoodsVo;
import com.liquidnet.service.goblin.service.IGoblinSqbGoodsService;
import com.liquidnet.service.goblin.util.GoblinRedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import com.liquidnet.service.goblin.param.shouqianba.request.GoblinSqbGoodsSyncParam;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 收钱吧商品同步 Controller
 */
@Slf4j
@Api(tags = "收钱吧商品同步")
@RestController
@RequestMapping("/sqb/goods")
public class GoblinSqbGoodsController {

    @Autowired
    IGoblinSqbGoodsService goblinSqbGoodsService;
    
    @Autowired
    GoblinRedisUtils goblinRedisUtils;

    /**
     * 查询所有商城及商品列表
     * 后端自动拉取所有商城，循环获取每个商城的商品列表，聚合返回前端
     */
    @GetMapping("/list")
    @ApiOperation("查询收钱吧所有商城及商品列表")
    public ResponseDto<List<GoblinSqbPerfGoodsVo>> list() {
        return goblinSqbGoodsService.getProductList();
    }

    /**
     * 批量新增收钱吧商品
     */
    @PostMapping("/add")
    @ApiOperation("批量新增收钱吧商品")
    public ResponseDto<String> addGoods(@RequestParam("storeId") String storeId,
                                        @RequestBody @Validated List<GoblinSqbPerfGoodsVo> items) {
        String currentUid = CurrentUtil.getCurrentUid();
        if (!goblinRedisUtils.hasStoreId(currentUid, storeId)) {
            log.warn("[收钱吧商品同步] 批量新增: 无权操作该店铺, uid={}, storeId={}", currentUid, storeId);
            return ResponseDto.failure("无权操作该店铺");
        }
        return goblinSqbGoodsService.addGoods(storeId, items);
    }

    /**
     * 批量更新收钱吧商品
     */
    @PostMapping("/update")
    @ApiOperation("批量更新收钱吧商品")
    public ResponseDto<String> updateGoods(@RequestParam("storeId") String storeId,
                                           @RequestBody @Validated List<GoblinSqbPerfGoodsVo> items) {
        String currentUid = CurrentUtil.getCurrentUid();
        if (!goblinRedisUtils.hasStoreId(currentUid, storeId)) {
            log.warn("[收钱吧商品同步] 批量更新: 无权操作该店铺, uid={}, storeId={}", currentUid, storeId);
            return ResponseDto.failure("无权操作该店铺");
        }
        return goblinSqbGoodsService.updateGoods(storeId, items);
    }

    /**
     * 查询演出关联商品列表（C端）
     * 先查 Redis 缓存（TTL 5min），未命中则查 MySQL 并写入缓存
     */
    @GetMapping("/performance/goods/{performancesId}")
    @ApiOperation("查询演出关联商品列表")
    public ResponseDto<List<GoblinSqbPerfGoodsVo>> getPerfGoods(@PathVariable String performancesId) {
        return goblinSqbGoodsService.getPerfGoods(performancesId);
    }
}
