package com.ikon.projectmanagement.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

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.transaction.annotation.Transactional;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.ikon.projectmanagement.dto.request.GradeRequestDto;
import com.ikon.projectmanagement.dto.response.GradeResponseDto;
import com.ikon.projectmanagement.entity.Grade;
import com.ikon.projectmanagement.mapper.GradeMapper;
import com.ikon.projectmanagement.repository.GradeRepository;
import com.ikon.projectmanagement.service.ImportGradeService;
import com.ikon.webservice.WebService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.UUID;

@Service
@RequiredArgsConstructor
@Slf4j
public class ImportGradeServiceImpl extends WebService implements ImportGradeService {

    private final GradeMapper gradeMapper;

    private final RestTemplate restTemplate;
    private final GradeRepository gradeRepository;

    @Value("${salescrm.api.base-url}")
    private String salesCrmBaseUrl;

    private HttpHeaders createHeaders(String accessToken) {
        HttpHeaders headers = new HttpHeaders();
        if (accessToken != null && !accessToken.isEmpty()) {
            headers.set("Authorization", accessToken);
        }
        headers.set("Content-Type", "application/json");
        return headers;
    }

    @Override
    @Transactional
    public List<GradeResponseDto> importGrades(String accessToken) {
        String url = salesCrmBaseUrl + "/grade";
        UUID accountId = getActiveAccountId();
        log.info("Fetching all grades from Sales CRM: {}", url);
        try {
            HttpEntity<Void> entity = new HttpEntity<>(createHeaders(accessToken));
            ResponseEntity<List<GradeRequestDto>> response = restTemplate.exchange(
                    url, HttpMethod.GET, entity, new ParameterizedTypeReference<List<GradeRequestDto>>() {});
            List<GradeRequestDto> dtos = response.getBody() != null ? response.getBody() : Collections.emptyList();
            List<GradeResponseDto> savedResponses = new ArrayList<>();

            List<Grade> entities = dtos.stream().map(dto -> Grade.builder()
                    .id(dto.getId())
                    .accountId(accountId)
                    .grade(dto.getGrade())
                    .build()).collect(Collectors.toList());

            if (!entities.isEmpty()) {
                gradeRepository.saveAll(entities);
                log.info("Saved/Updated {} grades", entities.size());
            }

            entities.forEach(g -> savedResponses.add(gradeMapper.toResponseDto(g)));
            return savedResponses;
        } catch (RestClientException e) {
            log.error("Failed to fetch grades from Sales CRM: {}", e.getMessage());
            return Collections.emptyList();
        }
    }
}
