package org.xyzh.auth.strategy.impl;

import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.xyzh.auth.strategy.LoginStrategy;
import org.xyzh.common.core.domain.LoginParam;
import org.xyzh.api.system.service.SysUserService;
import org.xyzh.api.system.vo.SysUserVO;

/**
 * @description    微信小程序登录策略
 * @filename    WechatMiniProgramLoginStrategy.java
 * @author    cascade
 * @copyright xyzh
 * @since 2025-12-22
 */
@Component
public class WechatMiniProgramLoginStrategy implements LoginStrategy {

    @Autowired
    private SysUserService userService;

    @Override
    public String getLoginType() {
        return "wechat_miniprogram";
    }

    @Override
    public boolean validate(LoginParam loginParam) {
        // 小程序登录需要wechatId或phone
        boolean hasWechatId = loginParam.getWechatId() != null && !loginParam.getWechatId().trim().isEmpty();
        boolean hasPhone = loginParam.getPhone() != null && !loginParam.getPhone().trim().isEmpty();
        return hasWechatId || hasPhone;
    }

    @Override
    public SysUserVO findUser(LoginParam loginParam) {
        SysUserVO filter = new SysUserVO();
        
        // 优先使用wechatId查询
        if (loginParam.getWechatId() != null && !loginParam.getWechatId().trim().isEmpty()) {
            filter.setWechatId(loginParam.getWechatId());
            SysUserVO user = userService.getLoginUser(filter).getData();
            if (user != null) {
                return user;
            }
        }
        
        // 如果wechatId未找到，尝试用phone查询
        if (loginParam.getPhone() != null && !loginParam.getPhone().trim().isEmpty()) {
            filter = new SysUserVO();
            filter.setPhone(loginParam.getPhone());
            SysUserVO user = userService.getLoginUser(filter).getData();
            if (user != null) {
                // 如果用户存在但没有wechatId，需要更新wechatId
                if (user.getWechatId() == null && loginParam.getWechatId() != null) {
                    SysUserVO updateUser = new SysUserVO();
                    updateUser.setUserId(user.getUserId());
                    updateUser.setWechatId(loginParam.getWechatId());
                    userService.updateUser(updateUser);
                    user.setWechatId(loginParam.getWechatId());
                }
                return user;
            }
        }
        
        return null;
    }

    @Override
    public boolean verifyCredential(String inputCredential, String storedCredential) {
        // 微信小程序通过微信授权，不需要密码验证
        return true;
    }
}
