package com.qqchen.deploy.backend.deploy.integration.impl;

import com.qqchen.deploy.backend.deploy.entity.ExternalSystem;
import com.qqchen.deploy.backend.system.enums.ExternalSystemTypeEnum;
import com.qqchen.deploy.backend.deploy.integration.IExternalSystemIntegration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.HttpClientErrorException;

@Slf4j
@Service
public class GitIntegration implements IExternalSystemIntegration {
    
    private final RestTemplate restTemplate = new RestTemplate();
    
    @Override
    public boolean testConnection(ExternalSystem system) {
        try {
            String url = system.getUrl() + "/api/v4/version";
            HttpHeaders headers = new HttpHeaders();
            headers.set("PRIVATE-TOKEN", system.getToken());
            
            HttpEntity<String> entity = new HttpEntity<>(headers);
            ResponseEntity<String> response = restTemplate.exchange(
                url, 
                HttpMethod.GET, 
                entity, 
                String.class
            );
            
            return response.getStatusCode() == HttpStatus.OK;
        } catch (HttpClientErrorException.Unauthorized e) {
            log.error("GitLab token authentication failed: {}", system.getUrl());
            return false;
        } catch (HttpClientErrorException.NotFound e) {
            log.error("GitLab API endpoint not found: {}", system.getUrl());
            return false;
        } catch (Exception e) {
            log.error("Failed to connect to GitLab: {}", system.getUrl(), e);
            return false;
        }
    }
    
    @Override
    public ExternalSystemTypeEnum getSystemType() {
        return ExternalSystemTypeEnum.GIT;
    }
} 