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.RoleRequestDto;
import com.ikon.projectmanagement.dto.response.RoleResponseDto;
import com.ikon.projectmanagement.entity.Role;
import com.ikon.projectmanagement.mapper.RoleMapper;
import com.ikon.projectmanagement.repository.RoleRepository;
import com.ikon.projectmanagement.service.ImportRoleService;
import com.ikon.webservice.WebService;

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

import java.util.UUID;

@Service
@RequiredArgsConstructor
@Slf4j
public class ImportRoleServiceImpl extends WebService implements ImportRoleService {

    private final RoleMapper roleMapper;

    private final RestTemplate restTemplate;
    private final RoleRepository roleRepository;

    @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<RoleResponseDto> importRoles(String accessToken) {
        String url = salesCrmBaseUrl + "/crm-role";
        UUID accountId = getActiveAccountId();
        log.info("Fetching all roles from Sales CRM: {}", url);
        try {
            HttpEntity<Void> entity = new HttpEntity<>(createHeaders(accessToken));
            ResponseEntity<List<RoleRequestDto>> response = restTemplate.exchange(
                    url, HttpMethod.GET, entity, new ParameterizedTypeReference<List<RoleRequestDto>>() {});
            List<RoleRequestDto> dtos = response.getBody() != null ? response.getBody() : Collections.emptyList();
            List<RoleResponseDto> savedResponses = new ArrayList<>();

            List<Role> entities = dtos.stream().map(dto -> Role.builder()
                    .id(dto.getId())
                    .accountId(accountId)
                    .role(dto.getRole())
                    .build()).collect(Collectors.toList());

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

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