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

import cn.novalon.gym.manage.auth.dto.PhoneCodeLoginDto;
import cn.novalon.gym.manage.auth.dto.PhoneLoginDto;
import cn.novalon.gym.manage.auth.dto.SendCodeRequest;
import cn.novalon.gym.manage.auth.service.PhoneAuthService;
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;

import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
@Tag(name = "手机号认证", description = "手机号一键登录与验证码登录")
public class PhoneAuthHandler {

    private final PhoneAuthService phoneAuthService;

    @Operation(summary = "手机号一键登录", description = "使用uniapp官方运营商认证，直接手机号登录或注册")
    public Mono<ServerResponse> oneClickLogin(ServerRequest request) {
        log.info("收到手机号一键登录请求");

        return request.bodyToMono(PhoneLoginDto.class)
                .flatMap(phoneAuthService::oneClickLogin)
                .flatMap(response -> ServerResponse.ok()
                        .contentType(MediaType.APPLICATION_JSON)
                        .bodyValue(response));
    }

    @Operation(summary = "发送短信验证码", description = "使用阿里云发送短信验证码")
    public Mono<ServerResponse> sendSmsCode(ServerRequest request) {
        log.info("收到发送短信验证码请求");

        return request.bodyToMono(SendCodeRequest.class)
                .flatMap(req -> phoneAuthService.sendSmsCode(req.getPhone()))
                .flatMap(success -> ServerResponse.ok()
                        .contentType(MediaType.APPLICATION_JSON)
                        .bodyValue(Map.of("success", success, "message", success ? "验证码发送成功" : "验证码发送失败")));
    }

    @Operation(summary = "手机号验证码登录", description = "使用阿里云短信验证码登录或注册")
    public Mono<ServerResponse> codeLogin(ServerRequest request) {
        log.info("收到手机号验证码登录请求");

        return request.bodyToMono(PhoneCodeLoginDto.class)
                .flatMap(phoneAuthService::codeLogin)
                .flatMap(response -> ServerResponse.ok()
                        .contentType(MediaType.APPLICATION_JSON)
                        .bodyValue(response));
    }
}