package com.qaup.collision.datacollector.service;


import com.qaup.collision.common.model.dto.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

@Slf4j
@Service
public class AuthService {

    @Value("${data.collector.airport-api.auth.username}")
    private String username;

    @Value("${data.collector.airport-api.auth.password}")
    private String password;

    @Value("${data.collector.airport-api.base-url}")
    private String baseUrl;

    @Value("${data.collector.airport-api.endpoints.login}")
    private String loginEndpoint;

    @Value("${data.collector.airport-api.endpoints.refresh}")
    private String refreshEndpoint;

    private final RestTemplate restTemplate;
    private String token;
    private long tokenExpiryTime;

    public AuthService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    //登录获取Token
    public String loginAndGetToken() {
        String loginUrl = UriComponentsBuilder
                .fromUriString(baseUrl)
                .path(loginEndpoint)
                .queryParam("username", username)
                .queryParam("password", password)
                .toUriString();

        try {
            ResponseEntity<Response<String>> response = restTemplate.exchange(
                loginUrl,
                HttpMethod.POST,
                null,
                    new ParameterizedTypeReference<Response<String>>() {
                    }
            );

            if (response.getStatusCode().is2xxSuccessful()) {
                Response<String> responseBody = response.getBody();
                if (responseBody != null) {
                    this.token = responseBody.getData();
                    this.tokenExpiryTime = System.currentTimeMillis() + 3600 * 1000;
                    log.info("Successfully obtained new token");
                    return this.token;
                }
            }
        } catch (Exception e) {
            log.error("Failed to login: ", e);
        }
        throw new RuntimeException("Failed to obtain token");
    }

    //Token续时
    public String refreshToken() {
        String refreshUrl = UriComponentsBuilder
                .fromUriString(baseUrl)
                .path(refreshEndpoint)
                .toUriString();

        try {
            // 创建带有当前token的请求头
            HttpEntity<?> requestEntity = new HttpEntity<>(createAuthHeader());

            ResponseEntity<Response<String>> response = restTemplate.exchange(
                refreshUrl,
                HttpMethod.GET,
                requestEntity,
                new ParameterizedTypeReference<Response<String>>() {}
            );

            if (response.getStatusCode().is2xxSuccessful()) {
                Response<String> responseBody = response.getBody();
                if (responseBody != null) {
                    this.token = responseBody.getData();
                    this.tokenExpiryTime = System.currentTimeMillis() + 3600 * 1000;
                    log.info("Successfully refreshed token");
                    return this.token;
                }
            }
        } catch (Exception e) {
            log.error("Failed to refresh token: ", e);
        }
        // 如果续期失败，尝试重新登录
        return loginAndGetToken();
    }

    //创造带有Token的请求头
    private HttpHeaders createAuthHeader() {
        HttpHeaders headers = new HttpHeaders();
        if (token != null) {
            headers.set("Authorization", token);
        }
        return headers;
    }

    //获取Token
    public String getToken() {
        long currentTime = System.currentTimeMillis();
        if (token == null) {
            return loginAndGetToken();
        }
        // 如果token已过期，重新登录
        if (currentTime >= tokenExpiryTime) {
            return loginAndGetToken();
        }
        // 如果token即将过期（比如还有10分钟过期），尝试续期
        if (currentTime >= tokenExpiryTime - 600_000) {
            return refreshToken();
        }
        return token;
    }
}
