package ru.soune.nocopy.repository;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import ru.soune.nocopy.entity.complaint.ComplaintEntity;
import ru.soune.nocopy.entity.complaint.ComplaintStatus;

import java.util.List;
import java.util.Optional;

@Repository
public interface ComplaintEntityRepository extends JpaRepository<ComplaintEntity, String> {
    Optional<ComplaintEntity> findById(Long id);
    Page<ComplaintEntity> findAll(Pageable pageable);
    Page<ComplaintEntity> findByStatus(ComplaintStatus status, Pageable pageable);
    ComplaintEntity findByViolationId(Long violationId);
    @Query("SELECT c FROM ComplaintEntity c WHERE c.violation.id = :violationId AND c.status IN :statuses")
    List<ComplaintEntity> findByViolationIdAndStatuses(@Param("violationId") Long violationId, @Param("statuses") List<String> statuses);
    boolean existsByViolationId(Long violationId);

    @Modifying
    @Transactional
    @Query("UPDATE ComplaintEntity c SET c.status = :status WHERE c.id = :id")
    int updateStatus(Long id, ComplaintStatus status);

    @Query("SELECT COUNT(c.id) FROM ComplaintEntity c")
    Long getTotalComplaintsCount();

    @Query("""
        SELECT COUNT(c.id) 
        FROM ComplaintEntity c 
        WHERE NOT EXISTS (
            SELECT 1 FROM LawCase lc WHERE lc.violationId = c.violation.id
        )
    """)
    Long getComplaintsWithoutLawCaseCount();

    @Query("SELECT COUNT(c) FROM ComplaintEntity c WHERE c.violation.id IN :violations")
    Long countComplaintByViolations(@Param("violations") List<Long> violations);

    @Query("SELECT c FROM ComplaintEntity c WHERE c.email IN :emails")
    Page<ComplaintEntity> getComplaintsByUserEmails(@Param("emails") List<String> emails, Pageable pageable);
}
