package com.ikon.projectmanagement.service.impl;

import com.ikon.projectmanagement.dto.response.WorkingDaysMonthDto;
import com.ikon.projectmanagement.dto.response.WorkingDaysResponseDto;
import com.ikon.projectmanagement.entity.WorkingDaysEntity;
import com.ikon.projectmanagement.repository.WorkingDaysRepository;
import com.ikon.projectmanagement.service.WorkingDayService;
import jakarta.persistence.EntityNotFoundException;
import java.util.HashMap;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class WorkingDayServiceImpl implements WorkingDayService {

    private final WorkingDaysRepository workingDayRepository;

    @Override
    public Page<WorkingDaysResponseDto> getAllWorkingDays(Pageable pageable) {
        return workingDayRepository.findAll(pageable)
                .map(this::mapToResponseDto);
    }

    @Override
    public WorkingDaysResponseDto getWorkingDaysByYear(String year) {
        WorkingDaysEntity entity = workingDayRepository.findByYear(year)
                .orElseThrow(() -> new EntityNotFoundException(
                        "Working days not found for year: " + year));

        return mapToResponseDto(entity);
    }

    private WorkingDaysResponseDto mapToResponseDto(WorkingDaysEntity entity) {
        Map<String, Map<String, WorkingDaysMonthDto>> detailsMap = new HashMap<>();

        entity.getWorkingDaysDetails().values().forEach(detail -> {
            WorkingDaysMonthDto monthDto = new WorkingDaysMonthDto();
            monthDto.setYear(detail.getYear());
            monthDto.setMonth(detail.getMonth());
            monthDto.setWorkingDays(detail.getWorkingDays());

            // outer key = year, inner key = month
            detailsMap
                    .computeIfAbsent(detail.getYear(), y -> new HashMap<>())
                    .put(detail.getMonth(), monthDto);
        });

        WorkingDaysResponseDto responseDto = new WorkingDaysResponseDto();
        responseDto.setWorkingDaysDetails(detailsMap);
        responseDto.setAccountIdentifier(entity.getAccountIdentifier());
        responseDto.setWorkingId(entity.getWorkingId());
        return responseDto;
    }
}
