namespace DocuMed.Repository.Handlers.MedicalHistories;

public class UpdateMedicalHistoryCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) : IRequestHandler<UpdateMedicalHistoryCommand, Guid>
{
    public async Task<Guid> Handle(UpdateMedicalHistoryCommand template, CancellationToken cancellationToken)
    {
        if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
            throw new AppException("دسترسی غیرمجاز", ApiResultStatusCode.UnAuthorized);

        var ent = await repositoryWrapper.SetRepository<MedicalHistory>().TableNoTracking
            .FirstOrDefaultAsync(m => m.Id == template.Id, cancellationToken);
        if(ent==null)
            throw new AppException("شرح حال پیدا نشد", ApiResultStatusCode.NotFound);
        var newEnt = MedicalHistory.Create(template.ChiefComplaint, template.SectionId,
            template.PresentIllnessDetail, template.PastDiseasesHistoryDetail, template.PastSurgeryHistoryDetail,
            template.FamilyHistoryDetail, template.AllergyDetail, template.DrugHistoryDetail,
            template.AddictionHistoryDetail, template.SystemReviewDetail, template.VitalSignDetail, template.GeneralAppearanceDetail,
            template.SystolicBloodPressure, template.DiastolicBloodPressure, template.PulseRate, template.SPO2,
            template.Temperature, template.ApplicationUserId, template.MedicalHistoryTemplateId);
        newEnt.Id = ent.Id;
        newEnt.CreatedAt = ent.CreatedAt;


        foreach (var answer in template.Answers.Where(a => a.Id == Guid.Empty))
            newEnt.AddAnswer(answer.Answer, answer.Question, answer.Part, answer.QuestionType);


        foreach (var answer in template.Answers.Where(a => a.Id != Guid.Empty))
        {
            var dbAnswer = await repositoryWrapper.SetRepository<MedicalHistoryAnswer>().TableNoTracking
                .FirstOrDefaultAsync(a => a.Id == answer.Id, cancellationToken);
            if (dbAnswer != null && dbAnswer.Answer != answer.Answer && answer.Answer != null)
            {
                dbAnswer = MedicalHistoryAnswer.Create(answer.Answer, answer.Question, answer.Part, answer.QuestionType,
                    dbAnswer.MedicalHistoryId);
                dbAnswer.Id = answer.Id;
                repositoryWrapper.SetRepository<MedicalHistoryAnswer>().Update(dbAnswer);
                await repositoryWrapper.SaveChangesAsync(cancellationToken);
            }
        }

        repositoryWrapper.SetRepository<MedicalHistory>().Update(newEnt);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);

        return newEnt.Id;
    }
}