#nullable enable
using Baya.Application.Common;
using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Persistence;
using Baya.Application.Models.Common;
using Baya.Application.Models.Identity;
using Baya.Domain.Entities.User;
using Mediator;

namespace Baya.Application.Features.Identity.Commands.UpdatePatient;

internal sealed class UpdatePatientCommandHandler(ICurrentUser currentUser, IUnitOfWork unitOfWork)
    : IRequestHandler<UpdatePatientCommand, OperationResult<PatientDto>>
{
    public async ValueTask<OperationResult<PatientDto>> Handle(UpdatePatientCommand request, CancellationToken cancellationToken)
    {
        if (currentUser.UserId is not { } userId)
            return OperationResult<PatientDto>.UnauthorizedResult("Not authenticated.");

        if (currentUser.Roles?.Contains(RoleNames.Customer) != true)
            return OperationResult<PatientDto>.ForbiddenResult("Only a customer can manage patients.");

        var customerId = await unitOfWork.CustomerProfileRepository.GetProfileIdByUserIdAsync(userId, cancellationToken);
        if (customerId is not { } cid)
            return OperationResult<PatientDto>.NotFoundResult("Patient not found.");

        var patient = await unitOfWork.PatientRepository.GetOwnedAsync(request.Id, cid, cancellationToken);
        if (patient is null)
            return OperationResult<PatientDto>.NotFoundResult("Patient not found.");

        patient.DisplayName = request.DisplayName;
        patient.FirstName = request.FirstName;
        patient.LastName = request.LastName;
        patient.BirthDate = request.BirthDate;
        patient.Gender = request.Gender;
        patient.BloodType = request.BloodType;
        patient.InitialMedicalNotes = request.InitialMedicalNotes;
        patient.Relation = request.Relation;
        patient.ConditionsJson = JsonCodeList.Serialize(request.Conditions);

        await unitOfWork.CommitAsync();

        return OperationResult<PatientDto>.SuccessResult(new PatientDto(
            patient.Id,
            patient.DisplayName,
            patient.FirstName,
            patient.LastName,
            patient.BirthDate,
            patient.Gender,
            patient.BloodType,
            patient.InitialMedicalNotes,
            patient.IsActive,
            patient.Relation,
            JsonCodeList.Parse(patient.ConditionsJson)));
    }
}
