package cn.novalon.gym.manage.groupcourse.handler;

import cn.novalon.gym.manage.groupcourse.domain.GroupCourseType;
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseTypeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
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;

import java.util.HashMap;
import java.util.Map;

@Component
@Tag(name = "团课类型管理", description = "团课类型及难度相关操作")
public class GroupCourseTypeHandler {

    private final IGroupCourseTypeService groupCourseTypeService;

    public GroupCourseTypeHandler(IGroupCourseTypeService groupCourseTypeService) {
        this.groupCourseTypeService = groupCourseTypeService;
    }

    @Operation(summary = "获取所有团课类型", description = "获取系统中所有团课类型列表")
    public Mono<ServerResponse> getAllGroupCourseTypes(ServerRequest request) {
        boolean includeDeleted = Boolean.valueOf(request.queryParam("includeDeleted").orElse("false"));
        return ServerResponse.ok()
                .body(groupCourseTypeService.findAll(includeDeleted), GroupCourseType.class);
    }

    @Operation(summary = "根据ID获取团课类型", description = "根据ID获取团课类型详情")
    public Mono<ServerResponse> getGroupCourseTypeById(ServerRequest request) {
        Long id = Long.valueOf(request.pathVariable("id"));
        return groupCourseTypeService.findById(id)
                .flatMap(type -> ServerResponse.ok().bodyValue(type))
                .switchIfEmpty(ServerResponse.notFound().build());
    }

    @Operation(summary = "根据关键词搜索团课类型", description = "根据类型名称关键词搜索团课类型")
    public Mono<ServerResponse> searchGroupCourseTypes(ServerRequest request) {
        String keyword = request.queryParam("keyword").orElse("");
        return ServerResponse.ok()
                .body(groupCourseTypeService.findByKeyword(keyword), GroupCourseType.class);
    }

    @Operation(summary = "根据分类获取团课类型", description = "根据分类获取团课类型列表")
    public Mono<ServerResponse> getGroupCourseTypesByCategory(ServerRequest request) {
        String category = request.pathVariable("category");
        String keyword = request.queryParam("keyword").orElse("");
        return ServerResponse.ok()
                .body(groupCourseTypeService.findByCategoryAndKeyword(category, keyword), GroupCourseType.class);
    }

    @Operation(summary = "获取所有分类", description = "获取所有团课类型分类（去重）")
    public Mono<ServerResponse> getCategories(ServerRequest request) {
        return groupCourseTypeService.findCategories()
                .collectList()
                .flatMap(list -> ServerResponse.ok().bodyValue(list));
    }

    @Operation(summary = "创建团课类型", description = "创建新的团课类型")
    public Mono<ServerResponse> createGroupCourseType(ServerRequest request) {
        return request.bodyToMono(GroupCourseType.class)
                .flatMap(groupCourseType -> {
                    if (groupCourseType.getTypeName() == null || groupCourseType.getTypeName().isEmpty()) {
                        Map<String, Object> error = new HashMap<>();
                        error.put("success", false);
                        error.put("message", "类型名称不能为空");
                        return ServerResponse.badRequest().bodyValue(error);
                    }
                    
                    // 默认基础难度为1
                    if (groupCourseType.getBaseDifficulty() == null) {
                        groupCourseType.setBaseDifficulty(1);
                    }
                    
                    return groupCourseTypeService.create(groupCourseType)
                            .flatMap(type -> {
                                Map<String, Object> response = new HashMap<>();
                                response.put("success", true);
                                response.put("message", "团课类型创建成功");
                                response.put("data", type);
                                return ServerResponse.ok().bodyValue(response);
                            })
                            .onErrorResume(error -> {
                                Map<String, Object> response = new HashMap<>();
                                response.put("success", false);
                                response.put("message", error.getMessage());
                                return ServerResponse.badRequest().bodyValue(response);
                            });
                });
    }

    @Operation(summary = "更新团课类型", description = "更新指定团课类型信息")
    public Mono<ServerResponse> updateGroupCourseType(ServerRequest request) {
        Long id = Long.valueOf(request.pathVariable("id"));
        
        return request.bodyToMono(GroupCourseType.class)
                .flatMap(groupCourseType -> {
                    groupCourseType.setId(id);
                    return groupCourseTypeService.update(id, groupCourseType)
                            .flatMap(type -> {
                                Map<String, Object> response = new HashMap<>();
                                response.put("success", true);
                                response.put("message", "团课类型更新成功");
                                response.put("data", type);
                                return ServerResponse.ok().bodyValue(response);
                            })
                            .onErrorResume(error -> {
                                Map<String, Object> response = new HashMap<>();
                                response.put("success", false);
                                response.put("message", error.getMessage());
                                return ServerResponse.badRequest().bodyValue(response);
                            });
                });
    }

    @Operation(summary = "删除团课类型", description = "删除指定团课类型（软删除）")
    public Mono<ServerResponse> deleteGroupCourseType(ServerRequest request) {
        Long id = Long.valueOf(request.pathVariable("id"));
        
        return groupCourseTypeService.delete(id)
                .then(Mono.defer(() -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", true);
                    response.put("message", "团课类型删除成功");
                    return ServerResponse.ok().bodyValue(response);
                }))
                .onErrorResume(error -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", false);
                    response.put("message", error.getMessage());
                    return ServerResponse.badRequest().bodyValue(response);
                });
    }
}