package com.aksenov.monitor.services;

import com.aksenov.monitor.data.Sales;
import com.aksenov.monitor.repositories.SalesRepository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

@Service
public class SalesService {

    private final SalesRepository repository;

    public SalesService(SalesRepository repository) {
        this.repository = repository;
    }

    public Optional<Sales> get(Long id) {
        return repository.findById(id);
    }

    public Sales save(Sales entity) {
        return repository.save(entity);
    }

    public void delete(Long id) {
        repository.deleteById(id);
    }

    public Page<Sales> list(Pageable pageable) {
        return repository.findAll(pageable);
    }

    public Page<Sales> list(Pageable pageable, Specification<Sales> filter) {
        return repository.findAll(filter, pageable);
    }

    public int count() {
        return (int) repository.count();
    }

    public List<Sales> list() {
        return repository.findAll();
    }

    public List<Sales> findSalesByMonthAndYear(int month, int year) {
        return repository.findAllBySaleDateMonthAndYear(month, year);
    }
    public Double getTotalSalesForMonthAndYear(int month, int year) {
        return repository.findTotalSalesByMonthAndYear(month, year);
    }

    public Map<String, Long> getSalesDataByModel() {
        Map<String, Long> salesData = new HashMap<>();
        List<Object[]> results = repository.getSalesStatisticsByModel();
        for (Object[] result : results) {
            String model = (String) result[0];
            Long total = (Long) result[1];
            salesData.put(model, total);
        }
        return salesData;
    }

}
