package com.haha.admin.controller;

import com.haha.admin.annotation.RequirePermission;
import com.haha.common.annotation.Log;
import com.haha.common.enums.OperationType;
import com.haha.common.vo.Result;
import com.haha.entity.ErpShop;
import com.haha.service.ErpShopService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * ERP 店铺管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/erp-shops")
@RequiredArgsConstructor
public class ErpShopController {

    private final ErpShopService erpShopService;

    /**
     * 从 ERP 同步店铺数据
     */
    @RequirePermission("erp:shop:sync")
    @Log(module = "ERP店铺管理", operation = OperationType.SYNC, summary = "同步ERP店铺数据")
    @PostMapping("/sync")
    public Result<Void> syncFromErp() {
        erpShopService.syncFromErp();
        return Result.success("同步成功");
    }

    /**
     * 查询已缓存的 ERP 店铺列表
     */
    @RequirePermission("erp:shop:read")
    @GetMapping
    public Result<List<ErpShop>> list() {
        return Result.success("查询成功", erpShopService.listAll());
    }

    /**
     * 绑定系统门店与 ERP 店铺
     */
    @RequirePermission("erp:shop:bind")
    @Log(module = "ERP店铺管理", operation = OperationType.UPDATE, summary = "绑定ERP店铺")
    @PostMapping("/bind")
    public Result<Void> bind(@RequestBody Map<String, Long> params) {
        Long shopId = params.get("shopId");
        Long erpShopId = params.get("erpShopId");
        if (shopId == null || erpShopId == null) {
            return Result.error("shopId 和 erpShopId 不能为空");
        }
        erpShopService.bindShop(shopId, erpShopId);
        return Result.success("绑定成功");
    }

    /**
     * 解除绑定
     */
    @RequirePermission("erp:shop:bind")
    @Log(module = "ERP店铺管理", operation = OperationType.UPDATE, summary = "解绑ERP店铺")
    @PostMapping("/unbind")
    public Result<Void> unbind(@RequestBody Map<String, Long> params) {
        Long shopId = params.get("shopId");
        if (shopId == null) {
            return Result.error("shopId 不能为空");
        }
        erpShopService.unbindShop(shopId);
        return Result.success("解绑成功");
    }
}
