package com.pharmacopoeia.service;

import com.pharmacopoeia.config.WechatProperties;
import com.pharmacopoeia.entity.User;
import com.pharmacopoeia.repository.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
public class AuthService {

    private final WechatProperties wechatProperties;
    private final UserRepository userRepository;
    private final RestTemplate restTemplate = new RestTemplate();

    public AuthService(WechatProperties wechatProperties, UserRepository userRepository) {
        this.wechatProperties = wechatProperties;
        this.userRepository = userRepository;
    }

    @Transactional
    public String wechatLogin(String code) {
        if (wechatProperties.getAppId() == null || wechatProperties.getAppId().isBlank()) {
            return "test-openid-" + code;
        }

        String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                wechatProperties.getAppId(), wechatProperties.getSecret(), code
        );
        @SuppressWarnings("unchecked")
        Map<String, Object> resp = restTemplate.getForObject(url, Map.class);
        if (resp != null && resp.containsKey("openid")) {
            String openid = (String) resp.get("openid");
            upsertUser(openid);
            return openid;
        }
        throw new RuntimeException("WeChat login failed: " + resp);
    }

    private void upsertUser(String openid) {
        userRepository.findByOpenid(openid).orElseGet(() ->
                userRepository.save(User.builder().openid(openid).build()));
    }
}
