package com.malk.guangming.service;

import com.malk.guangming.config.GuangmingConfig;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Contacts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service
public class DingTalkAuthService {

    @Autowired
    private GuangmingConfig config;

    @Autowired
    private DDClient ddClient;

    @Autowired
    private DDClient_Contacts ddClientContacts;

    /**
     * 通过免登授权码获取用户userId
     *
     * @param authCode 前端JSAPI获取的免登授权码
     * @return 用户userId
     */
    public String getUserId(String authCode) {
        String accessToken = ddClient.getAccessToken(
                config.getDingtalk().getAppKey(),
                config.getDingtalk().getAppSecret());
        Map userInfo = ddClient.getUserInfoByCode(accessToken, authCode);
        return userInfo.get("userid").toString();
    }

    /**
     * 根据userId获取用户邮箱
     *
     * @param userId 钉钉用户ID
     * @return 用户企业邮箱
     */
    public String getUserEmail(String userId) {
        String accessToken = ddClient.getAccessToken(
                config.getDingtalk().getAppKey(),
                config.getDingtalk().getAppSecret());
        Map userInfo = ddClientContacts.getUserInfoById(accessToken, userId);
        // 优先取企业邮箱(org_email)，其次取个人邮箱(email)
        Object orgEmail = userInfo.get("org_email");
        if (orgEmail != null && !orgEmail.toString().isEmpty()) {
            return orgEmail.toString();
        }
        Object email = userInfo.get("email");
        if (email != null && !email.toString().isEmpty()) {
            return email.toString();
        }
        log.error("[钉钉] 用户 {} 未配置邮箱, 返回字段: {}", userId, userInfo.keySet());
        throw new RuntimeException("该用户未配置企业邮箱");
    }
}
