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

import cn.novalon.gym.manage.member.dto.WechatLoginDto;
import cn.novalon.gym.manage.member.service.WechatAuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
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-05-01
 */

@Slf4j
@Component
@RequiredArgsConstructor
@Tag(name = "微信认证", description = "微信小程序登录、公众号回调等")
public class WechatAuthHandler {

    private final WechatAuthService wechatAuthService;
    private final WechatOfficialEventHandler wechatOfficialEventHandler;

    @Operation(summary = "微信小程序登录", description = "通过微信小程序code获取session_key，完成会员登录或注册")
    public Mono<ServerResponse> miniappLogin(ServerRequest request) {
        log.info("收到小程序登录请求");
        
        return request.bodyToMono(WechatLoginDto.class)
                .flatMap(loginRequest -> {
                    log.info("开始微信AuthService, code: {}", loginRequest.getCode());
                    return wechatAuthService.miniappLogin(loginRequest);
                })
                .flatMap(response -> {
                    log.info("更新成功, memberId: {}", response.getMemberId());
                    return ServerResponse.ok()
                            .contentType(MediaType.APPLICATION_JSON)
                            .bodyValue(response);
                });
    }

    @Operation(summary = "微信公众号回调", description = "处理微信公众号事件（关注、取消关注等）")
    public Mono<ServerResponse> mpCallback(ServerRequest request) {
        return wechatOfficialEventHandler.handleEvent(request);
    }

    @Operation(summary = "验证微信公众号签名", description = "微信公众号服务器验证，返回echostr")
    public Mono<ServerResponse> verifyMpSignature(ServerRequest request) {
        return wechatOfficialEventHandler.verifySignature(request);
    }
}
