package io.delphiplatform.api.v3.rdb.service.spotify;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
@Transactional(readOnly = true)
public class SpotifyTracksChartChangesService {

    public static final LocalDate DEFAULT_PREV_DATE_WHEN_NO_DATA = LocalDate.EPOCH;

    private final SpotifyChartTrackService spotifyChartTrackService;

    @Autowired
    public SpotifyTracksChartChangesService(SpotifyChartTrackService spotifyChartTrackService) {
        this.spotifyChartTrackService = spotifyChartTrackService;
    }

    public LocalDate getRequestedDateOrDefault(LocalDate requestDate, List<String> isrc, List<String> trackId) {
        if (requestDate != null) {
            return requestDate;
        }

        LocalDate earliestDateBefore = spotifyChartTrackService.getEarliestDateBefore(null, isrc, trackId);

        if (earliestDateBefore != null) {
            return earliestDateBefore;
        }

        return DEFAULT_PREV_DATE_WHEN_NO_DATA;
    }

    public LocalDate getDefaultPreviousDateDaily(LocalDate requestedDate) {
        return requestedDate.minusDays(1);
    }

    public LocalDate getDefaultPreviousDateWeekly(LocalDate requestedDate) {
        return requestedDate.minusDays(7);
    }
}
