package com.gameplatform.server.controller.admin;

import com.gameplatform.server.model.dto.common.PageResult;
import com.gameplatform.server.model.entity.admin.SystemConfig;
import com.gameplatform.server.model.dto.admin.SystemConfigRequest;
import com.gameplatform.server.model.dto.admin.SystemConfigResponse;
import com.gameplatform.server.model.dto.admin.SystemConfigConverter;
import com.gameplatform.server.model.dto.admin.BatchSystemConfigRequest;
import com.gameplatform.server.service.admin.SystemConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.ArrayList;

@RestController
@RequestMapping("/api/admin/config")
@Tag(name = "系统配置管理", description = "系统配置的增删改查接口")
public class SystemConfigController {
    
    @Autowired
    private SystemConfigService systemConfigService;
    
    @GetMapping("/list")
    @Operation(summary = "获取配置列表", description = "分页获取所有系统配置")
    public ResponseEntity<PageResult<SystemConfigResponse>> getConfigList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {
        
        int offset = (page - 1) * size;
        List<SystemConfig> configs = systemConfigService.getAllConfigs(size, offset);
        long total = systemConfigService.getConfigCount();
        
        List<SystemConfigResponse> responses = configs.stream()
                .map(SystemConfigConverter::toResponse)
                .toList();
        
        PageResult<SystemConfigResponse> result = new PageResult<>();
        result.setItems(responses);
        result.setTotal(total);
        result.setPage(page);
        result.setSize(size);
        
        return ResponseEntity.ok(result);
    }
    
    @GetMapping("/key/{configKey}")
    @Operation(summary = "根据键获取配置", description = "根据配置键获取配置信息")
    public ResponseEntity<SystemConfigResponse> getConfigByKey(@PathVariable String configKey) {
        SystemConfig config = systemConfigService.getConfigByKey(configKey);
        if (config == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(SystemConfigConverter.toResponse(config));
    }
    
    @GetMapping("/type/{configType}")
    @Operation(summary = "根据类型获取配置", description = "根据配置类型获取配置列表")
    public ResponseEntity<List<SystemConfigResponse>> getConfigsByType(@PathVariable String configType) {
        List<SystemConfig> configs = systemConfigService.getConfigsByType(configType);
        List<SystemConfigResponse> responses = configs.stream()
                .map(SystemConfigConverter::toResponse)
                .toList();
        return ResponseEntity.ok(responses);
    }
    
    @PostMapping
    @Operation(summary = "创建配置", description = "创建新的系统配置")
    public ResponseEntity<Boolean> createConfig(@RequestBody SystemConfigRequest request) {
        SystemConfig systemConfig = SystemConfigConverter.toEntity(request);
        boolean success = systemConfigService.createConfig(systemConfig);
        return ResponseEntity.ok(success);
    }
    
    @PutMapping("/{id}")
    @Operation(summary = "更新配置", description = "更新指定ID的系统配置")
    public ResponseEntity<Boolean> updateConfig(@PathVariable Long id, @RequestBody SystemConfigRequest request) {
        SystemConfig systemConfig = SystemConfigConverter.toEntity(request);
        systemConfig.setId(id);
        boolean success = systemConfigService.updateConfig(systemConfig);
        return ResponseEntity.ok(success);
    }
    
    @DeleteMapping("/{id}")
    @Operation(summary = "删除配置", description = "删除指定ID的系统配置")
    public ResponseEntity<Boolean> deleteConfig(@PathVariable Long id) {
        boolean success = systemConfigService.deleteConfig(id);
        return ResponseEntity.ok(success);
    }
    
    @DeleteMapping("/key/{configKey}")
    @Operation(summary = "根据键删除配置", description = "根据配置键删除系统配置")
    public ResponseEntity<Boolean> deleteConfigByKey(@PathVariable String configKey) {
        boolean success = systemConfigService.deleteConfigByKey(configKey);
        return ResponseEntity.ok(success);
    }
    
    @GetMapping("/link/defaults")
    @Operation(summary = "获取链接默认配置", description = "获取链接生成相关的默认配置")
    public ResponseEntity<Object> getLinkDefaults() {
        return ResponseEntity.ok(new Object() {
            public final Integer defaultQuantity = systemConfigService.getDefaultQuantity();
            public final Integer refreshInterval = systemConfigService.getRefreshInterval();
            public final Integer qrExpireTime = systemConfigService.getQrExpireTime();
        });
    }
    
    @GetMapping("/script/config")
    @Operation(summary = "获取脚本配置", description = "获取脚本服务器相关配置")
    public ResponseEntity<Object> getScriptConfig() {
        return ResponseEntity.ok(new Object() {
            public final String serverUrl = systemConfigService.getScriptServerUrl();
            public final String qrPathTemplate = systemConfigService.getQrPathTemplate();
        });
    }
    
    @GetMapping("/user/config")
    @Operation(summary = "获取用户端配置", description = "获取用户端相关配置")
    public ResponseEntity<Object> getUserConfig() {
        return ResponseEntity.ok(new Object() {
            public final Integer qrExpireSeconds = systemConfigService.getUserQrExpireSeconds();
            public final Integer refreshWaitSeconds = systemConfigService.getUserRefreshWaitSeconds();
            public final Integer linkExpireHours = systemConfigService.getUserLinkExpireHours();
            public final String assetsBaseUrl = systemConfigService.getUserAssetsBaseUrl();
        });
    }
    
    @PostMapping("/batch")
    @Operation(summary = "批量更新配置", description = "批量更新系统配置，支持根据配置键更新")
    public ResponseEntity<Object> batchUpdateConfigs(@RequestBody BatchSystemConfigRequest request) {
        if (request.getConfigs() == null || request.getConfigs().isEmpty()) {
            return ResponseEntity.badRequest().body(new Object() {
                public final boolean success = false;
                public final String message = "配置列表不能为空";
            });
        }
        
        List<SystemConfig> configs = new ArrayList<>();
        List<String> validationErrors = new ArrayList<>();
        
        for (BatchSystemConfigRequest.SystemConfigUpdateItem item : request.getConfigs()) {
            // 验证配置值
            if (item.getConfigType() != null && item.getConfigValue() != null) {
                if (!systemConfigService.validateConfigValue(item.getConfigType(), item.getConfigValue())) {
                    validationErrors.add("配置键 " + item.getConfigKey() + " 的值格式不正确");
                    continue;
                }
            }
            
            SystemConfig config = new SystemConfig();
            config.setConfigKey(item.getConfigKey());
            config.setConfigValue(item.getConfigValue());
            config.setConfigType(item.getConfigType());
            config.setDescription(item.getDescription());
            configs.add(config);
        }
        
        if (!validationErrors.isEmpty()) {
            return ResponseEntity.badRequest().body(new Object() {
                public final boolean success = false;
                public final String message = "配置验证失败";
                public final List<String> errors = validationErrors;
            });
        }
        
        boolean success = systemConfigService.updateConfigs(configs);
        final boolean finalSuccess = success;
        final int finalUpdatedCount = configs.size();
        
        return ResponseEntity.ok(new Object() {
            public final boolean success = finalSuccess;
            public final String message = finalSuccess ? "批量更新成功" : "批量更新失败";
            public final int updatedCount = finalUpdatedCount;
        });
    }
    
    @PutMapping("/key/{configKey}")
    @Operation(summary = "根据键更新配置值", description = "根据配置键快速更新配置值")
    public ResponseEntity<Object> updateConfigByKey(
            @PathVariable String configKey, 
            @RequestBody String configValue) {
        
        // 先获取现有配置以验证类型
        SystemConfig existingConfig = systemConfigService.getConfigByKey(configKey);
        if (existingConfig == null) {
            return ResponseEntity.notFound().build();
        }
        
        // 验证配置值格式
        if (!systemConfigService.validateConfigValue(existingConfig.getConfigType(), configValue)) {
            return ResponseEntity.badRequest().body(new Object() {
                public final boolean success = false;
                public final String message = "配置值格式不正确，期望类型: " + existingConfig.getConfigType();
            });
        }
        
        boolean success = systemConfigService.updateConfigValueByKey(configKey, configValue);
        final boolean finalSuccess = success;
        
        return ResponseEntity.ok(new Object() {
            public final boolean success = finalSuccess;
            public final String message = finalSuccess ? "更新成功" : "更新失败";
        });
    }
}
