package com.haha.miniapp.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.haha.common.constant.ResponseEnum;
import com.haha.common.vo.Result;
import com.haha.entity.dto.PhoneLoginDTO;
import com.haha.service.LoginService;
import com.haha.common.vo.LoginVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/login")
@SaIgnore
public class LoginController {

    private final LoginService loginService;

    /**
     * 微信小程序手机号快速登录
     * 使用button open-type="getPhoneNumber"获取手机号
     */
    @PostMapping("/miniapp-phone")
    public Result<LoginVO> miniappPhoneLogin(@RequestBody PhoneLoginDTO dto) {
        String code = dto.getCode();         // 用于获取openid
        String phoneCode = dto.getPhoneCode(); // 用于获取手机号

        log.info("[登录] 微信小程序手机号快速登录请求 - code: {}, hasPhoneCode: {}",
                code != null ? code.substring(0, Math.min(8, code.length())) + "..." : "null",
                phoneCode != null);

        if (code == null || code.isEmpty()) {
            log.warn("[登录] 微信小程序手机号登录失败 - code为空");
            return ResponseEnum.PARAM_REQUIRED.toResult("登录凭证不能为空");
        }
        if (phoneCode == null || phoneCode.isEmpty()) {
            log.warn("[登录] 微信小程序手机号登录失败 - phoneCode为空");
            return ResponseEnum.PARAM_REQUIRED.toResult("手机号凭证不能为空");
        }

        try {
            Result<LoginVO> result = loginService.wechatMiniappPhoneLogin(code, phoneCode);
            return result;
        } catch (Exception e) {
            log.error("[登录] 登录异常", e);
            return Result.error("登录异常：" + e.getMessage());
        }
    }


    @PostMapping("/logout")
    public Result<Void> logout() {
        try {
            Object userId = StpUtil.getLoginIdDefaultNull();
            log.info("[登录] 用户退出登录 - userId: {}", userId);
            StpUtil.logout();
            return Result.success("退出登录成功");
        } catch (Exception e) {
            log.error("[登录] 退出登录异常", e);
            return Result.success("退出登录成功");
        }
    }

    @PostMapping("/user-info")
    public Result<Map<String, Object>> getUserInfo() {
        Object userId = StpUtil.getLoginId();
        log.debug("[登录] 获取用户信息 - userId: {}", userId);
        return loginService.getUserInfo(userId.toString());
    }
}
