package com.erp.tenant.controller.feature;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.erp.common.core.model.ApiResponse;
import com.erp.tenant.entity.feature.FeatureFlag;
import com.erp.tenant.service.feature.FeatureFlagService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 功能开关控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/features")
@RequiredArgsConstructor
public class FeatureFlagController {

    private final FeatureFlagService featureFlagService;

    /**
     * 分页查询功能开关
     */
    @GetMapping
    public ApiResponse<IPage<FeatureFlag>> listFeatureFlags(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "15") Integer pageSize,
            @RequestParam(required = false) Long tenantId,
            @RequestParam(required = false) Long packageId) {
        return ApiResponse.success(featureFlagService.listFeatureFlags(page, pageSize, tenantId, packageId));
    }

    /**
     * 获取租户的功能开关配置
     */
    @GetMapping("/tenant/{tenantId}")
    public ApiResponse<Map<String, Boolean>> getTenantFeatures(@PathVariable Long tenantId) {
        return ApiResponse.success(featureFlagService.getTenantFeatures(tenantId));
    }

    /**
     * 检查租户是否启用某个功能
     */
    @GetMapping("/tenant/{tenantId}/check/{featureKey}")
    public ApiResponse<Map<String, Object>> checkFeature(
            @PathVariable Long tenantId,
            @PathVariable String featureKey) {
        boolean enabled = featureFlagService.isFeatureEnabled(tenantId, featureKey);
        return ApiResponse.success(Map.of("featureKey", featureKey, "enabled", enabled));
    }

    /**
     * 创建功能开关
     */
    @PostMapping
    public ApiResponse<FeatureFlag> createFeatureFlag(@RequestBody FeatureFlag flag) {
        return ApiResponse.success("创建成功", featureFlagService.createFeatureFlag(flag));
    }

    /**
     * 更新功能开关
     */
    @PutMapping("/{id}")
    public ApiResponse<FeatureFlag> updateFeatureFlag(
            @PathVariable Long id,
            @RequestBody UpdateFeatureFlagRequest request) {
        return ApiResponse.success("更新成功",
                featureFlagService.updateFeatureFlag(id, request.getEnabled(),
                        request.getDescription(), request.getSort()));
    }

    /**
     * 切换功能开关状态（动态刷新）
     */
    @PostMapping("/{id}/toggle")
    public ApiResponse<Map<String, Object>> toggleFeatureFlag(@PathVariable Long id) {
        FeatureFlag flag = featureFlagService.toggleFeatureFlag(id);
        return ApiResponse.success("切换成功", Map.of(
                "id", flag.getId(),
                "featureKey", flag.getFeatureKey(),
                "enabled", flag.getEnabled()
        ));
    }

    /**
     * 删除功能开关
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteFeatureFlag(@PathVariable Long id) {
        featureFlagService.deleteFeatureFlag(id);
        return ApiResponse.success("删除成功", null);
    }

    /**
     * 刷新所有租户的功能开关缓存
     */
    @PostMapping("/refresh-cache")
    public ApiResponse<Void> refreshAllCaches() {
        featureFlagService.refreshAllCaches();
        return ApiResponse.success("缓存已刷新", null);
    }

    // ==================== 请求DTO ====================

    @lombok.Data
    @lombok.NoArgsConstructor
    @lombok.AllArgsConstructor
    public static class UpdateFeatureFlagRequest {
        private Boolean enabled;
        private String description;
        private Integer sort;
    }
}
