package com.lesingle.modules.pub.controller;

import com.lesingle.common.annotation.RateLimit;
import com.lesingle.common.result.Result;
import com.lesingle.common.util.SecurityUtil;
import com.lesingle.modules.pub.dto.PublicLoginDto;
import com.lesingle.modules.pub.dto.PublicRegisterDto;
import com.lesingle.modules.pub.dto.PublicSmsLoginDto;
import com.lesingle.modules.pub.dto.SendSmsCodeDto;
import com.lesingle.modules.pub.service.PublicAuthService;
import com.lesingle.modules.pub.service.SmsCodeService;
import com.lesingle.security.annotation.Public;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "公众端认证")
@RestController
@RequestMapping("/public/auth")
@RequiredArgsConstructor
public class PublicAuthController {

    private final PublicAuthService publicAuthService;
    private final SmsCodeService smsCodeService;

    @Public
    @PostMapping("/register")
    @RateLimit(permits = 5, duration = 1)
    @Operation(summary = "公众端注册")
    public Result<Map<String, Object>> register(@Valid @RequestBody PublicRegisterDto dto) {
        return Result.success(publicAuthService.register(dto));
    }

    @Public
    @PostMapping("/login")
    @RateLimit(permits = 5, duration = 1)
    @Operation(summary = "公众端登录")
    public Result<Map<String, Object>> login(@Valid @RequestBody PublicLoginDto dto) {
        return Result.success(publicAuthService.login(dto));
    }

    @Public
    @PostMapping("/login/sms")
    @RateLimit(permits = 5, duration = 1)
    @Operation(summary = "手机号验证码登录")
    public Result<Map<String, Object>> loginBySms(@Valid @RequestBody PublicSmsLoginDto dto) {
        return Result.success(publicAuthService.loginBySms(dto));
    }

    @Public
    @PostMapping("/sms/send")
    @RateLimit(permits = 1, duration = 60)
    @Operation(summary = "发送短信验证码")
    public Result<Void> sendSmsCode(@Valid @RequestBody SendSmsCodeDto dto) {
        smsCodeService.sendCode(dto.getPhone());
        return Result.success(null);
    }

    @PostMapping("/switch-child")
    @Operation(summary = "切换到子女账号")
    public Result<Map<String, Object>> switchChild(@RequestBody Map<String, Long> body) {
        Long parentUserId = SecurityUtil.getCurrentUserId();
        Long childUserId = body.get("childUserId");
        return Result.success(publicAuthService.switchChild(parentUserId, childUserId));
    }
}
