package com.magistr.app.repository;

import com.magistr.app.model.AcademicYear;
import jakarta.persistence.LockModeType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

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

public interface AcademicYearRepository extends JpaRepository<AcademicYear, Long> {

    Optional<AcademicYear> findByTitle(String title);

    boolean existsByTitle(String title);

    boolean existsByTitleAndIdNot(String title, Long id);

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("select year from AcademicYear year where year.id = :id")
    Optional<AcademicYear> findByIdForUpdate(@Param("id") Long id);

    @Query("""
            select case when count(year) > 0 then true else false end
            from AcademicYear year
            where year.startDate <= :endDate
              and year.endDate >= :startDate
            """)
    boolean existsOverlapping(@Param("startDate") LocalDate startDate,
                              @Param("endDate") LocalDate endDate);

    @Query("""
            select case when count(year) > 0 then true else false end
            from AcademicYear year
            where year.id <> :excludedId
              and year.startDate <= :endDate
              and year.endDate >= :startDate
            """)
    boolean existsOverlappingExcluding(@Param("excludedId") Long excludedId,
                                       @Param("startDate") LocalDate startDate,
                                       @Param("endDate") LocalDate endDate);
}
