package com.magistr.app.repository;

import com.magistr.app.model.TeacherDepartmentAssignment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

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

public interface TeacherDepartmentAssignmentRepository extends JpaRepository<TeacherDepartmentAssignment, Long> {

    @Query("""
            select a
            from TeacherDepartmentAssignment a
            join fetch a.teacher
            join fetch a.department
            where a.teacher.id = :teacherId
            order by a.validFrom desc, a.id desc
            """)
    List<TeacherDepartmentAssignment> findHistoryByTeacherId(@Param("teacherId") Long teacherId);

    @Query("""
            select a
            from TeacherDepartmentAssignment a
            join fetch a.teacher
            join fetch a.department
            where a.teacher.id = :teacherId
              and a.primaryAssignment = true
              and a.validTo is null
            """)
    Optional<TeacherDepartmentAssignment> findOpenPrimaryByTeacherId(@Param("teacherId") Long teacherId);

    @Query("""
            select a
            from TeacherDepartmentAssignment a
            join fetch a.teacher
            join fetch a.department
            where a.department.id = :departmentId
              and a.validFrom <= :date
              and (a.validTo is null or a.validTo >= :date)
            order by a.teacher.fullName
            """)
    List<TeacherDepartmentAssignment> findDepartmentTeachersAtDate(
            @Param("departmentId") Long departmentId,
            @Param("date") LocalDate date
    );

    @Query("""
            select count(a) > 0
            from TeacherDepartmentAssignment a
            where a.teacher.id = :teacherId
              and a.department.id = :departmentId
              and a.validFrom <= :date
              and (a.validTo is null or a.validTo >= :date)
            """)
    boolean existsActiveAssignment(
            @Param("teacherId") Long teacherId,
            @Param("departmentId") Long departmentId,
            @Param("date") LocalDate date
    );
}
