using DocuMed.Domain.Entities.MedicalHistoryTemplate;
using DocuMed.Repository.Repositories.Entities;
using DocuMed.Repository.Repositories.Entities.Abstracts;
using System.Threading;

namespace DocuMed.Core.EntityServices;

public class MedicalHistoryTemplateService(
    IRepositoryWrapper repositoryWrapper,
    ICurrentUserService currentUserService,
    IMedicalHistoryTemplateRepository medicalHistoryTemplateRepository)
    : IMedicalHistoryTemplateService
{
    public async Task<bool> EditAsync(MedicalHistoryTemplateLDto template, CancellationToken cancellationToken)
    {
        if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
            throw new AppException("توکن غیرمجاز", ApiResultStatusCode.UnAuthorized);
        if (template.Id==Guid.Empty)
            throw new AppException("پیش نویس پیدا نشد", ApiResultStatusCode.NotFound);
        var ent = MedicalHistoryTemplate.Create(template.ChiefComplaint, template.SectionId, userId);
        ent.Id = template.Id;

        var questions = await repositoryWrapper.SetRepository<MedicalHistoryQuestion>()
            .TableNoTracking
            .Where(q => q.MedicalHistoryTemplateId == ent.Id)
            .ToListAsync(cancellationToken);
        foreach (var question in questions)
        {
            if (template.Questions.FirstOrDefault(q => q.Id == question.Id) == null)
            {
                repositoryWrapper.SetRepository<MedicalHistoryQuestion>()
                    .Delete(question);
                await repositoryWrapper.SaveChangesAsync(cancellationToken);
            }
        }

        foreach (var question in template.Questions.Where(q=>q.Id==Guid.Empty))
            ent.AddQuestion(question.Question, question.Part, question.QuestionType,question.BodySystem,question.IsSign,question.IsSymptom);
        medicalHistoryTemplateRepository.Update(ent);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);
        return true;
    }

    public async Task<bool> AddAsync(MedicalHistoryTemplateLDto template,CancellationToken cancellationToken)
    {
        if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
            throw new AppException("توکن غیرمجاز", ApiResultStatusCode.UnAuthorized);
        var ent = MedicalHistoryTemplate.Create(template.ChiefComplaint, template.SectionId, userId);
        foreach (var question in template.Questions)
            ent.AddQuestion(question.Question, question.Part, question.QuestionType, question.BodySystem, question.IsSign, question.IsSymptom);
        medicalHistoryTemplateRepository.Add(ent);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);
        return true;
    }
}