package com.magistr.app.repository;

import com.magistr.app.model.Semester;
import com.magistr.app.model.SemesterType;
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.Collection;
import java.util.List;
import java.util.Optional;

public interface SemesterRepository extends JpaRepository<Semester, Long> {

    Optional<Semester> findFirstByStartDateLessThanEqualAndEndDateGreaterThanEqual(LocalDate startDate, LocalDate endDate);

    List<Semester> findByAcademicYearIdOrderByStartDateAsc(Long academicYearId);

    Optional<Semester> findByAcademicYearIdAndSemesterType(Long academicYearId, SemesterType semesterType);

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

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("""
            select semester
            from Semester semester
            where semester.id in :ids
            order by semester.id
            """)
    List<Semester> findAllByIdForUpdateOrderById(@Param("ids") Collection<Long> ids);
}
