package cn.novalon.gym.manage.sys.handler.config;

import cn.novalon.gym.manage.sys.core.domain.SysConfig;
import cn.novalon.gym.manage.sys.core.service.ISysConfigService;
import cn.novalon.gym.manage.sys.core.util.ValidationUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * 系统配置处理器
 * 
 * @author 张翔
 * @date 2026-03-14
 */
@Component
@Tag(name = "配置管理", description = "系统配置相关操作")
public class SysConfigHandler {

    private final ISysConfigService configService;

    public SysConfigHandler(ISysConfigService configService) {
        this.configService = configService;
    }

    @Operation(summary = "获取所有配置", description = "获取系统中所有配置列表")
    public Mono<ServerResponse> getAllConfigs(ServerRequest request) {
        return ServerResponse.ok()
                .body(configService.findAll(), SysConfig.class);
    }

    @Operation(summary = "根据ID获取配置", description = "根据配置ID获取配置详细信息")
    public Mono<ServerResponse> getConfigById(ServerRequest request) {
        return ValidationUtil.validateId(request.pathVariable("id"))
                .flatMap(configService::findById)
                .flatMap(config -> ServerResponse.ok().bodyValue(config))
                .switchIfEmpty(ServerResponse.notFound().build())
                .onErrorResume(IllegalArgumentException.class, e -> ValidationUtil.createErrorResponse(e.getMessage()));
    }

    @Operation(summary = "根据键获取配置", description = "根据配置键获取配置详细信息")
    public Mono<ServerResponse> getConfigByKey(ServerRequest request) {
        String configKey = request.pathVariable("configKey");
        if (!ValidationUtil.isValidConfigKey(configKey)) {
            return ValidationUtil.createErrorResponse("配置键格式无效");
        }
        return configService.findByConfigKey(configKey)
                .flatMap(config -> ServerResponse.ok().bodyValue(config))
                .switchIfEmpty(ServerResponse.notFound().build());
    }

    @Operation(summary = "创建配置", description = "创建新配置")
    public Mono<ServerResponse> createConfig(ServerRequest request) {
        return request.bodyToMono(SysConfig.class)
                .flatMap(ValidationUtil::validateConfig)
                .flatMap(configService::save)
                .flatMap(config -> ServerResponse.status(HttpStatus.CREATED).bodyValue(config))
                .onErrorResume(IllegalArgumentException.class, e -> ValidationUtil.createErrorResponse(e.getMessage()));
    }

    @Operation(summary = "更新配置", description = "更新配置信息")
    public Mono<ServerResponse> updateConfig(ServerRequest request) {
        return ValidationUtil.validateId(request.pathVariable("id"))
                .flatMap(id -> request.bodyToMono(SysConfig.class)
                        .flatMap(ValidationUtil::validateConfig)
                        .flatMap(config -> configService.findById(id)
                                .flatMap(existing -> {
                                    existing.setConfigName(config.getConfigName());
                                    existing.setConfigValue(config.getConfigValue());
                                    existing.setConfigType(config.getConfigType());
                                    return configService.save(existing);
                                })))
                .flatMap(updatedConfig -> ServerResponse.ok().bodyValue(updatedConfig))
                .switchIfEmpty(ServerResponse.notFound().build())
                .onErrorResume(IllegalArgumentException.class, e -> ValidationUtil.createErrorResponse(e.getMessage()));
    }

    @Operation(summary = "删除配置", description = "删除指定配置")
    public Mono<ServerResponse> deleteConfig(ServerRequest request) {
        return ValidationUtil.validateId(request.pathVariable("id"))
                .flatMap(id -> configService.deleteById(id)
                        .then(ServerResponse.noContent().build()))
                .onErrorResume(IllegalArgumentException.class, e -> ValidationUtil.createErrorResponse(e.getMessage()));
    }
}
