package de.votian.services.repository;

import de.votian.services.entity.Job;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

public interface JobRepository extends JpaRepository<Job, Long> {

    List<Job> findByHeadquartersId(Long hqId);

    List<Job> findByHeadquartersIdAndStatusInOrderByOrderTimeAscIdAsc(Long hqId, Collection<Integer> statuses);

    List<Job> findByStatus(Integer status);

    List<Job> findByCourierId(Long courierId);

    @Query("SELECT DISTINCT j FROM Job j LEFT JOIN Tour t ON j.id = t.jobId " +
           "WHERE j.costCenterPayerId IN :cscIds OR j.costCenterPayerCashId IN :cscIds " +
           "OR ((j.costCenterPayerId IS NULL OR j.costCenterPayerId = 0) AND t.costCenterId IN :cscIds) " +
           "ORDER BY j.id DESC")
    List<Job> findByPayerCostCenters(@Param("cscIds") List<Long> cscIds);

    @Query("SELECT j FROM Job j WHERE j.orderTime >= :from AND j.orderTime <= :to AND j.headquartersId = :hqId ORDER BY j.id DESC")
    List<Job> findByOrderTimeBetweenAndHq(@Param("from") LocalDateTime from, @Param("to") LocalDateTime to, @Param("hqId") Long hqId);

    @Query("SELECT j FROM Job j JOIN Tour t ON j.id = t.jobId " +
           "WHERE t.commissionNo = :commNo AND t.sort = 1 AND j.costCenterPayerId IN " +
           "(SELECT csc.id FROM CostCenter csc WHERE csc.customerId = :csId) ORDER BY j.id DESC")
    List<Job> findByCommissionNoAndCustomer(@Param("commNo") String commNo, @Param("csId") Long csId);

    @Query("SELECT j FROM Job j WHERE j.orderTime >= CURRENT_DATE")
    List<Job> findTodaysJobs();

    @Query("SELECT j FROM Job j WHERE j.copyPermanentId IS NOT NULL AND j.orderTime > :since " +
           "AND (j.costCenterPayerId IN :cscIds OR j.costCenterPayerCashId IN :cscIds) ORDER BY j.id")
    List<Job> findPermanentCopies(@Param("since") LocalDateTime since, @Param("cscIds") List<Long> cscIds);

    @Query("SELECT j FROM Job j WHERE (j.headquartersId = :hqId OR j.headquartersDispoId = :hqId) " +
           "AND j.orderTime >= :from AND j.orderTime <= :to ORDER BY j.orderTime, j.id")
    List<Job> findForDispositionDay(@Param("hqId") Long hqId,
                                    @Param("from") LocalDateTime from,
                                    @Param("to") LocalDateTime to);
}
