using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;

namespace Jiaowu.Api.Infrastructure.Experiments;

internal static class CentralizedExperimentConflictQuery
{
    public static IQueryable<Guid> TaskIdsForTeachers(
        AppDbContext db,
        IReadOnlyCollection<Guid> teacherIds) =>
        db.TeachingTaskTeachers.AsNoTracking()
            .WhereIn(teacherIds, x => x.TeacherId)
            .Select(x => x.TeachingTaskId);

    public static IQueryable<Guid> TaskIdsForClasses(
        AppDbContext db,
        IReadOnlyCollection<Guid> classIds) =>
        db.TeachingTaskClasses.AsNoTracking()
            .WhereIn(classIds, x => x.AdministrativeClassId)
            .Select(x => x.TeachingTaskId);

    public static IQueryable<ScheduleEntry> ScheduleEntries(
        AppDbContext db,
        IReadOnlyCollection<Guid> relatedTaskIds,
        Guid academicTermId,
        int dayOfWeek,
        int week,
        int startPeriod,
        int periodCount) =>
        db.ScheduleEntries.AsNoTracking()
            .Where(x =>
                x.SchedulePlan!.Status == SchedulePlanStatus.Published &&
                x.SchedulePlan.AcademicTermId == academicTermId &&
                x.DayOfWeek == dayOfWeek &&
                x.StartWeek <= week &&
                x.EndWeek >= week &&
                x.StartPeriod < startPeriod + periodCount &&
                startPeriod < x.StartPeriod + x.PeriodCount)
            .WhereIn(relatedTaskIds, x => x.TeachingTaskId);

    public static IQueryable<ExperimentSession> ExperimentSessions(
        AppDbContext db,
        IReadOnlyCollection<Guid> relatedTaskIds,
        DateOnly date,
        int startPeriod,
        int periodCount) =>
        db.ExperimentSessions.AsNoTracking()
            .Where(x =>
                x.Status == ExperimentSessionStatus.Scheduled &&
                x.SessionDate == date &&
                x.StartPeriod < startPeriod + periodCount &&
                startPeriod < x.StartPeriod + x.PeriodCount &&
                x.ExperimentProject!.ArrangementMode ==
                    ExperimentArrangementMode.Centralized)
            .WhereIn(
                relatedTaskIds,
                x => x.ExperimentProject!.TeachingTaskId);
}
