package com.smyhub.store.mengyastorebackendjava.service;

import com.smyhub.store.mengyastorebackendjava.config.AppProperties;
import com.smyhub.store.mengyastorebackendjava.security.SproutGateVerifyResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class SproutGateAuthService {

    private final RestTemplate restTemplate;
    private final AppProperties appProperties;

    public SproutGateVerifyResult verifyToken(String token) {
        try {
            String url = appProperties.getAuthApiUrl() + "/api/auth/verify";
            ResponseEntity<SproutGateVerifyResult> resp = restTemplate.postForEntity(
                    url, Map.of("token", token), SproutGateVerifyResult.class
            );
            if (resp.getStatusCode().is2xxSuccessful() && resp.getBody() != null) {
                return resp.getBody();
            }
        } catch (Exception e) {
            log.warn("[SproutGate] token verify failed: {}", e.getMessage());
        }
        SproutGateVerifyResult invalid = new SproutGateVerifyResult();
        invalid.setValid(false);
        return invalid;
    }
}
