using DocuMed.Api.Services;
using DocuMed.Domain.Dtos.LargDtos;

namespace DocuMed.Api.Controllers;

public class MedicalHistoryTemplateController : ICarterModule
{
    public virtual void AddRoutes(IEndpointRouteBuilder app)
    {
        var group = app.NewVersionedApi("MedicalHistoryTemplate").MapGroup($"api/medicalhistory/template")
            .RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser());

        group.MapGet("", GetAllAsync)
            .WithDisplayName("GetAll")
            .HasApiVersion(1.0);

        group.MapGet("{id}", GetAsync)
            .WithDisplayName("GetOne")
            .HasApiVersion(1.0);

        group.MapPost("", Post)
            .HasApiVersion(1.0);

        group.MapPut("", Put)
            .HasApiVersion(1.0);

        group.MapDelete("", Delete)
            .HasApiVersion(1.0);
    }


    // GET:Get All Entity
    public virtual async Task<IResult> GetAllAsync([FromQuery] int page, IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService, CancellationToken cancellationToken)
    {
        if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
            throw new AppException("توکن غیرمجاز", ApiResultStatusCode.UnAuthorized);
        var list = await repositoryWrapper.SetRepository<MedicalHistoryTemplate>().TableNoTracking
            .Where(t=>t.ApplicationUserId== userId)
            .OrderByDescending(t=>t.CreatedAt)
            .Skip(page*15)
            .Take(15)
            .Select(MedicalHistoryTemplateMapper.ProjectToSDto)
            .ToListAsync(cancellationToken);
        return TypedResults.Ok(list);
    }

    // GET:Get An Entity By Id
    public async Task<IResult> GetAsync(Guid id, IRepositoryWrapper repositoryWrapper,
        CancellationToken cancellationToken)
        => TypedResults.Ok(await repositoryWrapper.SetRepository<MedicalHistoryTemplate>()
            .GetByIdAsync(cancellationToken, id));

    // POST:Add New Entity
    public virtual async Task<IResult> Post([FromBody] MedicalHistoryTemplateLDto dto, IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService, CancellationToken cancellationToken)
    {
        if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
            throw new AppException("توکن غیرمجاز", ApiResultStatusCode.UnAuthorized);
        var ent = MedicalHistoryTemplate.Create(dto.ChiefComplaint,dto.SectionId, userId);
        foreach (var question in dto.Questions)
            ent.AddQuestion(question.Question, question.Part, question.QuestionType);
        repositoryWrapper.SetRepository<MedicalHistoryTemplate>().Add(ent);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);
        return TypedResults.Ok();
    }

    // PUT:Update Entity
    public virtual async Task<IResult> Put([FromBody] MedicalHistoryTemplateLDto dto, IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService, CancellationToken cancellationToken)
    {
        if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
            throw new AppException("توکن غیرمجاز", ApiResultStatusCode.UnAuthorized);
        var ent = MedicalHistoryTemplate.Create(dto.ChiefComplaint, dto.SectionId, userId);
        ent.Id = dto.Id;
        repositoryWrapper.SetRepository<MedicalHistoryTemplate>().Update(ent);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);
        return TypedResults.Ok();
    }

    // DELETE:Delete Entity
    public virtual async Task<IResult> Delete(int id, IRepositoryWrapper repositoryWrapper, CancellationToken cancellationToken)
    {
        var ent = await repositoryWrapper.SetRepository<MedicalHistoryTemplate>().GetByIdAsync(cancellationToken, id);
        repositoryWrapper.SetRepository<MedicalHistoryTemplate>().Delete(ent);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);
        return TypedResults.Ok();
    }
}