package com.haha.miniapp.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.haha.common.vo.Result;
import com.haha.service.LoginService;
import com.haha.common.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
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;

@RestController
@RequestMapping("/login")
@SaIgnore // 忽略当前类所有方法的登录校验
public class LoginController {
    
    @Autowired
    private LoginService loginService;
    
    /**
     * 账号密码登录（临时方案）
     * @param params 包含phone和password的参数
     * @return 登录结果，包含token和用户信息
     */
    @PostMapping("/password")
    public Result<LoginVO> loginByPassword(@RequestBody Map<String, String> params) {
        String phone = params.get("phone");
        String password = params.get("password");
        return loginService.loginByPassword(phone, password);
    }
    
    /**
     * 微信手机号快捷登录
     * @param params 包含code和encryptedData、iv的参数
     * @return 登录结果，包含token和用户信息
     */
    @PostMapping("/wechat-phone")
    public Result<LoginVO> wechatPhoneLogin(@RequestBody Map<String, String> params) {
        String code = params.get("code");
        String encryptedData = params.get("encryptedData");
        String iv = params.get("iv");
        
        return loginService.wechatPhoneLogin(code, encryptedData, iv);
    }
    
    /**
     * 退出登录
     * @return 退出结果
     */
    @PostMapping("/logout")
    public Result<Void> logout() {
        StpUtil.logout();
        return Result.success("退出登录成功", null);
    }
    
    /**
     * 获取当前登录用户信息
     * @return 用户信息
     */
    @PostMapping("/user-info")
    public Result<Map<String, Object>> getUserInfo() {
        Object userId = StpUtil.getLoginId();
        return loginService.getUserInfo(userId.toString());
    }
}