package com.petshop.backend.repository;

import com.petshop.backend.entity.Adoption;
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.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

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

@Repository
public interface AdoptionRepository extends JpaRepository<Adoption, Long> {

    @Query("SELECT a FROM Adoption a WHERE " +
           "(:q IS NULL OR (" +
           "LOWER(a.customer.firstName) LIKE LOWER(CONCAT('%', :q, '%')) OR " +
           "LOWER(a.customer.lastName) LIKE LOWER(CONCAT('%', :q, '%')) OR " +
           "LOWER(a.pet.petName) LIKE LOWER(CONCAT('%', :q, '%'))" +
           ")) AND " +
           "(:customerId IS NULL OR a.customer.id = :customerId) AND " +
           "(:status IS NULL OR LOWER(a.adoptionStatus) = LOWER(:status)) AND " +
           "(:storeId IS NULL OR a.sourceStore.storeId = :storeId) AND " +
           "(:date IS NULL OR a.adoptionDate = :date)")
    Page<Adoption> searchAdoptions(
            @Param("q") String query,
            @Param("customerId") Long customerId,
            @Param("status") String status,
            @Param("storeId") Long storeId,
            @Param("date") LocalDate date,
            Pageable pageable);

    Optional<Adoption> findFirstByPet_IdAndAdoptionStatusOrderByAdoptionDateDesc(Long petId, String adoptionStatus);

    boolean existsByPet_IdAndAdoptionStatusIgnoreCaseAndAdoptionIdNot(Long petId, String adoptionStatus, Long adoptionId);

    boolean existsByPet_IdAndAdoptionStatusIgnoreCase(Long petId, String adoptionStatus);

    List<Adoption> findByCustomer_IdAndAdoptionStatusIgnoreCase(Long customerId, String adoptionStatus);

    List<Adoption> findByAdoptionDateAndAdoptionStatusIgnoreCase(LocalDate date, String status);
}
