package de.nilzbu.mytimetracker.service;

import de.nilzbu.mytimetracker.model.TimeEntry;
import de.nilzbu.mytimetracker.model.User;
import de.nilzbu.mytimetracker.repository.TimeEntryRepository;
import org.springframework.stereotype.Service;

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

@Service
public class TimeEntryService {

    private final TimeEntryRepository repository;

    public TimeEntryService(TimeEntryRepository repository) {
        this.repository = repository;
    }

    public List<TimeEntry> getEntriesForUser(User user) {
        return repository.findAllByUserOrderByDateDesc(user);
    }

    public TimeEntry save(TimeEntry entry) {
        return repository.save(entry);
    }

    public int calculateNetWorkMinutes(TimeEntry entry) {
        if (entry.getStartTime() == null || entry.getEndTime() == null) {
            return 0;
        }
        long total = Duration.between(entry.getStartTime(), entry.getEndTime()).toMinutes();
        return (int)(total - entry.getPauseMinutes());
    }

    public long calculateDeviation(TimeEntry entry) {
        return calculateNetWorkMinutes(entry) - entry.getTargetMinutes();
    }

    public void delete(TimeEntry entry) {
        repository.delete(entry);
    }

    public List<TimeEntry> getEntriesForMonth(User user, int year, int month) {
        LocalDate start = LocalDate.of(year, month, 1);
        LocalDate end = start.withDayOfMonth(start.lengthOfMonth());
        return repository.findByUserAndDateBetween(user, start, end);
    }

    public List<TimeEntry> getEntriesForQuarter(User user, int year, int quarter) {
        int startMonth = (quarter - 1) * 3 + 1;
        LocalDate start = LocalDate.of(year, startMonth, 1);
        LocalDate end = start.plusMonths(2).withDayOfMonth(start.plusMonths(2).lengthOfMonth());
        return repository.findByUserAndDateBetween(user, start, end);
    }

    public List<TimeEntry> getEntriesForYear(User user, int year) {
        LocalDate start = LocalDate.of(year, 1, 1);
        LocalDate end = LocalDate.of(year, 12, 31);
        return repository.findByUserAndDateBetween(user, start, end);
    }

    public Optional<LocalDate> getEarliestEntryDate(User user) {
        return repository.findFirstByUserOrderByDateAsc(user)
                .map(TimeEntry::getDate);
    }
}