package ru.nbch.credit_tracker.service.indic;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import ru.nbch.credit_tracker.entities.dto.PhoneFidMap;
import ru.nbch.credit_tracker.mapper.indic.PhoneMapper;

import java.time.LocalDate;
import java.util.*;

@Slf4j
@Service
public class PhoneService {

    private final PhoneMapper mapper;

    public PhoneService(PhoneMapper mapper) {
        this.mapper = mapper;
    }

    /**
     * Ищет фиды по номерам телефона
     * @return Map: key - fid; value - {@link PhoneFidMap}
     */
    public Map<Integer, PhoneFidMap> defineFidByPhone(List<PhoneFidMap> subjects) {
        Map<Integer, PhoneFidMap> phoneFidMap = new HashMap<>();
        List<String> phones = subjects.stream().
            map(subject -> "9" + subject.getPhone())
            .toList();

        subjects.sort(
            Comparator.comparing(
                PhoneFidMap::getPhone,
                Comparator.naturalOrder()
            )
        );

        //отсортированный список по NUMBER, FID и FILE_SINCE_DT
        List<FidsData> phonesByFid = mapper.findFids(phones);
        log.debug("Start merging fids");
        for (PhoneFidMap phoneFid : subjects) {
            Iterator<FidsData> iterator = phonesByFid.iterator();
            while (iterator.hasNext()) {
                FidsData fidsData = iterator.next();
                if (fidsData.getPhone().equals(9 + phoneFid.getPhone())) {
                    //fixme доступ по ссылке, страшно, придумать что-то еще
                    phoneFidMap.put(fidsData.getFid(), phoneFid);
                    iterator.remove();
                    break;
                }
            }
        }
        log.debug("End merging fids");

        return phoneFidMap;
    }

    @Getter
    @Setter
    @AllArgsConstructor
    @NoArgsConstructor
    public static class FidsData {
        private Integer fid;
        private String phone;
        private LocalDate fileSinceDate;
    }
}
