using EntityFrameworkCore.Triggered;
using IRaCIS.Core.Domain.Share;

namespace IRaCIS.Core.Application.Triggers
{

    /// <summary>
    /// 访视 质疑状态  触发修改
    /// </summary>
    /// <param name="_qcChallengeRepository"></param>
    /// <param name="_subjectVisitRepository"></param>
    public class ChallengeStateTrigger(IRepository<QCChallenge> _qcChallengeRepository, IRepository<SubjectVisit> _subjectVisitRepository) : IAfterSaveTrigger<QCChallenge>
    {


        public async Task AfterSave(ITriggerContext<QCChallenge> context, CancellationToken cancellationToken)
        {
            var subjectVisitId = context.Entity.SubjectVisitId;

            ChallengeStateEnum subjectVisitChallengeState = default;


            var closedStateList = await _qcChallengeRepository.Where(t => t.SubjectVisitId == subjectVisitId).Select(t => t.IsClosed).ToListAsync();

            if (closedStateList.Count == 0)
            {
                subjectVisitChallengeState = ChallengeStateEnum.No;
            }
            else if (closedStateList.All(t => t is true))
            {
                subjectVisitChallengeState = ChallengeStateEnum.HaveAndAllClosed;
            }
            else
            {
                subjectVisitChallengeState = ChallengeStateEnum.HaveAndHaveNotClosed;
            }


            await _subjectVisitRepository.BatchUpdateNoTrackingAsync(t => t.Id == subjectVisitId,
                u => new SubjectVisit() { ChallengeState = subjectVisitChallengeState });
        }
    }




}