namespace DocuMed.Repository.Handlers.MedicalHistories;

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

        var ent = 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, userId, template.MedicalHistoryTemplateId);

        foreach (var answer in template.Answers)
            ent.AddAnswer(answer.Answer, answer.Question, answer.Part, answer.QuestionType);

        repositoryWrapper.SetRepository<MedicalHistory>().Add(ent);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);
        return ent.Id;
    }
}