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.response.WorkingDayDto;
import com.ikon.projectmanagement.entity.WorkingDaysEntity;
import com.ikon.projectmanagement.repository.WorkingDaysRepository;
import com.ikon.projectmanagement.service.ImportWorkingDayService;
import com.ikon.webservice.WebService;

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

import java.util.UUID;

@Service
@RequiredArgsConstructor
@Slf4j
public class ImportWorkingDayServiceImpl extends WebService implements ImportWorkingDayService {

    private final RestTemplate restTemplate;
    private final WorkingDaysRepository workingDayRepository;

    @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;
    }

    private static final int PAGE_SIZE = 200;

    @Override
    @Transactional
    public List<WorkingDayDto> importWorkingDays(String accessToken) {
        String baseUrl = salesCrmBaseUrl + "/workingday";
        UUID accountId = getActiveAccountId();
        log.info("Fetching all working days from Sales CRM: {}", baseUrl);
        try {
            HttpEntity<Void> entity = new HttpEntity<>(createHeaders(accessToken));
            List<WorkingDayDto> allDtos = new ArrayList<>();
            int page = 0;
            int totalPages = 1;

            while (page < totalPages) {
                String url = baseUrl + "?page=" + page + "&size=" + PAGE_SIZE;
                ResponseEntity<PageResponse<WorkingDayDto>> response = restTemplate.exchange(
                        url, HttpMethod.GET, entity, new ParameterizedTypeReference<PageResponse<WorkingDayDto>>() {
                        });

                if (response.getBody() == null || response.getBody().getContent() == null) {
                    break;
                }

                PageResponse<WorkingDayDto> body = response.getBody();
                allDtos.addAll(body.getContent());
                totalPages = body.getTotalPages();
                log.info("Fetched working days page {}/{}", page + 1, totalPages);
                page++;
            }

            // List<WorkingDaysEntity> entities = allDtos.stream().map(dto ->
            // WorkingDaysEntity.builder()
            // .id(dto.getId())
            // .accountId(accountId)
            // .year(dto.getYear())
            // .month(dto.getMonth())
            // .workingDays(dto.getWorkingDays())
            // .build()).collect(Collectors.toList());

            // if (!entities.isEmpty()) {
            // workingDayRepository.saveAll(entities);
            // log.info("Saved/Updated {} working days in total", entities.size());
            // }

            return allDtos;
        } catch (RestClientException e) {
            log.error("Failed to fetch working days from Sales CRM: {}", e.getMessage());
            return Collections.emptyList();
        }
    }

    @Data
    public static class PageResponse<T> {
        private List<T> content;
        private int totalPages;
        private long totalElements;
    }
}
