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

import cn.novalon.gym.manage.groupcourse.domain.GroupCourseRecommend;
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseRecommendService;
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 GroupCourseRecommendHandler {

    private final IGroupCourseRecommendService recommendService;

    public GroupCourseRecommendHandler(IGroupCourseRecommendService recommendService) {
        this.recommendService = recommendService;
    }

    @Operation(summary = "获取所有团课推荐", description = "获取系统中所有团课推荐列表，支持按优先级排序")
    public Mono<ServerResponse> getAllRecommendations(ServerRequest request) {
        String sortBy = request.queryParam("sortBy").orElse("priority");
        String sortOrder = request.queryParam("sortOrder").orElse("desc");

        return ServerResponse.ok()
                .body(recommendService.findAll(sortBy, sortOrder), GroupCourseRecommend.class);
    }

    @Operation(summary = "获取所有启用的团课推荐", description = "获取系统中所有已启用的团课推荐列表（按优先级排序）")
    public Mono<ServerResponse> getAllActiveRecommendations(ServerRequest request) {
        return ServerResponse.ok()
                .body(recommendService.findAllActive(), GroupCourseRecommend.class);
    }

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

    @Operation(summary = "根据团课ID获取推荐", description = "根据团课ID获取该团课的推荐信息")
    public Mono<ServerResponse> getRecommendationsByCourseId(ServerRequest request) {
        Long courseId = Long.valueOf(request.pathVariable("courseId"));
        return ServerResponse.ok()
                .body(recommendService.findByCourseId(courseId), GroupCourseRecommend.class);
    }

    @Operation(summary = "创建团课推荐", description = "创建新的团课推荐")
    public Mono<ServerResponse> createRecommendation(ServerRequest request) {
        return request.bodyToMono(GroupCourseRecommend.class)
                .flatMap(recommend -> {
                    if (recommend.getCourseId() == null) {
                        Map<String, Object> error = new HashMap<>();
                        error.put("success", false);
                        error.put("message", "团课ID不能为空");
                        return ServerResponse.badRequest().bodyValue(error);
                    }

                    return recommendService.create(recommend)
                            .flatMap(r -> {
                                Map<String, Object> response = new HashMap<>();
                                response.put("success", true);
                                response.put("message", "团课推荐创建成功");
                                response.put("data", r);
                                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> updateRecommendation(ServerRequest request) {
        Long id = Long.valueOf(request.pathVariable("id"));

        return request.bodyToMono(GroupCourseRecommend.class)
                .flatMap(recommend -> {
                    return recommendService.update(id, recommend)
                            .flatMap(r -> {
                                Map<String, Object> response = new HashMap<>();
                                response.put("success", true);
                                response.put("message", "团课推荐更新成功");
                                response.put("data", r);
                                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> deleteRecommendation(ServerRequest request) {
        Long id = Long.valueOf(request.pathVariable("id"));

        return recommendService.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);
                });
    }

    @Operation(summary = "启用团课推荐", description = "启用指定团课推荐")
    public Mono<ServerResponse> enableRecommendation(ServerRequest request) {
        Long id = Long.valueOf(request.pathVariable("id"));

        return recommendService.enable(id)
                .flatMap(r -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", true);
                    response.put("message", "团课推荐启用成功");
                    response.put("data", r);
                    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> disableRecommendation(ServerRequest request) {
        Long id = Long.valueOf(request.pathVariable("id"));

        return recommendService.disable(id)
                .flatMap(r -> {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", true);
                    response.put("message", "团课推荐禁用成功");
                    response.put("data", r);
                    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);
                });
    }
}