package com.ikon.projectmanagement.service.impl;

import java.util.HashMap;
import java.util.Map;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.ikon.projectmanagement.dto.response.FxRateDetailsDto;
import com.ikon.projectmanagement.dto.response.FxRateResponseDto;
import com.ikon.projectmanagement.entity.FxRateEntity;
import com.ikon.projectmanagement.repository.FxRateRepository;
import com.ikon.projectmanagement.service.FxRateService;
import com.ikon.webservice.WebService;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class FxRateServiceImpl extends WebService implements FxRateService {

    private final FxRateRepository fxRateRepository;

    @Override
    public Page<FxRateResponseDto> getAllFxRates(Pageable pageable) {
        return fxRateRepository.findAll(pageable)
                .map(this::mapToResponseDto);
    }

    @Override
    public FxRateResponseDto getFxRateByYear(String year) {
        FxRateEntity entity = fxRateRepository.findByYear(year)
                .orElseThrow(() -> new EntityNotFoundException(
                        "FX rate not found for year: " + year));

        return mapToResponseDto(entity);
    }

    // -------------------------------------------------------------------------
    // Private helpers
    // ------------------------------------------------------------------------

    private FxRateResponseDto mapToResponseDto(FxRateEntity entity) {
        Map<String, Map<String, FxRateDetailsDto>> detailsMap = new HashMap<>();

        entity.getFxRateDetails().values().forEach(detail -> {
            FxRateDetailsDto dto = new FxRateDetailsDto();
            dto.setId(detail.getCurrencyId());
            dto.setCurrency(detail.getCurrency());
            dto.setFxRate(detail.getFxRate());
            dto.setActiveStatus(detail.getActiveStatus());
            dto.setYear(detail.getYear());

            detailsMap
                    .computeIfAbsent(detail.getYear(), y -> new HashMap<>())
                    .put(detail.getCurrencyId(), dto);
        });

        FxRateResponseDto responseDto = new FxRateResponseDto();
        responseDto.setFxRateId(entity.getFxRateId());
        responseDto.setAccountIdentifier(entity.getAccountIdentifier());
        responseDto.setFxRateDetails(detailsMap);
        return responseDto;
    }
}