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

import cn.novalon.gym.manage.groupcourse.domain.GroupCourseBooking;
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseBookingService;
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;

/**
 * 团课预约Handler
 * 
 * @author 张翔
 * @date 2026-06-01
 */
@Component
@Tag(name = "团课预约", description = "团课预约相关操作")
public class GroupCourseBookingHandler {

    private final IGroupCourseBookingService bookingService;

    public GroupCourseBookingHandler(IGroupCourseBookingService bookingService) {
        this.bookingService = bookingService;
    }

    /**
     * 预约团课
     */
    @Operation(summary = "预约团课", description = "会员预约指定团课")
    public Mono<ServerResponse> bookCourse(ServerRequest request) {
        return request.bodyToMono(Map.class)
                .flatMap(body -> {
                    // 验证必填参数
                    if (body.get("courseId") == null) {
                        return buildErrorResponse("请提供课程ID");
                    }
                    if (body.get("memberId") == null) {
                        return buildErrorResponse("请提供会员ID");
                    }
                    if (body.get("memberCardRecordId") == null) {
                        return buildErrorResponse("请提供会员卡记录ID");
                    }

                    Long courseId = ((Number) body.get("courseId")).longValue();
                    Long memberId = ((Number) body.get("memberId")).longValue();
                    Long memberCardRecordId = ((Number) body.get("memberCardRecordId")).longValue();

                    return bookingService.bookCourse(courseId, memberId, memberCardRecordId)
                            .flatMap(booking -> {
                                Map<String, Object> response = new HashMap<>();
                                response.put("success", true);
                                response.put("message", "预约成功");
                                response.put("data", booking);
                                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> cancelBooking(ServerRequest request) {
        Long bookingId = Long.valueOf(request.pathVariable("bookingId"));

        return request.bodyToMono(Map.class)
                .flatMap(body -> {
                    Long memberId = ((Number) body.get("memberId")).longValue();

                    return bookingService.cancelBooking(bookingId, memberId)
                            .flatMap(booking -> {
                                Map<String, Object> response = new HashMap<>();
                                response.put("success", true);
                                response.put("message", "取消成功");
                                response.put("data", booking);
                                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 = "根据会员ID查询所有预约记录")
    public Mono<ServerResponse> getBookingsByMemberId(ServerRequest request) {
        Long memberId = Long.valueOf(request.pathVariable("memberId"));

        return ServerResponse.ok()
                .body(bookingService.getBookingsByMemberId(memberId), GroupCourseBooking.class);
    }

    /**
     * 查询预约详情
     */
    @Operation(summary = "查询预约详情", description = "根据预约ID查询预约详情")
    public Mono<ServerResponse> getBookingById(ServerRequest request) {
        Long bookingId = Long.valueOf(request.pathVariable("bookingId"));

        return bookingService.getBookingById(bookingId)
                .flatMap(booking -> ServerResponse.ok().bodyValue(booking))
                .switchIfEmpty(ServerResponse.notFound().build());
    }

    /**
     * 查询课程预约记录
     */
    @Operation(summary = "查询课程预约记录", description = "根据团课ID查询所有预约记录")
    public Mono<ServerResponse> getBookingsByCourseId(ServerRequest request) {
        Long courseId = Long.valueOf(request.pathVariable("courseId"));

        return ServerResponse.ok()
                .body(bookingService.getBookingsByCourseId(courseId), GroupCourseBooking.class);
    }

    /**
     * 构建错误响应
     */
    private Mono<ServerResponse> buildErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return ServerResponse.badRequest().bodyValue(response);
    }
}