using Knot.Shared.Kernel;
using Knot.Contracts.Profiles.Domain;
using Knot.Contracts.Profiles.Application.DTOs;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Knot.Modules.Profiles.Application.Profiles.UpdateProfile;

public sealed record UpdateProfileCommand(
    Guid UserId,
    string? DisplayName,
    string? Bio,
    DateTime? Birthday) : ICommand<UserProfileDto>;

internal sealed class UpdateProfileCommandHandler : ICommandHandler<UpdateProfileCommand, UserProfileDto>
{
    private readonly IProfileRepository _repository;

    public UpdateProfileCommandHandler(IProfileRepository repository)
    {
        _repository = repository;
    }

    public async Task<Result<UserProfileDto>> Handle(UpdateProfileCommand request, CancellationToken cancellationToken)
    {
        var profile = await _repository.GetAsync(request.UserId, cancellationToken);
        if (profile is null)
            return Result.Failure<UserProfileDto>(ProfilesErrors.ProfileNotFound);

        profile.DisplayName = request.DisplayName ?? profile.DisplayName;
        profile.About = request.Bio;
        profile.Birthday = request.Birthday;

        var result = await _repository.UpdateAsync(profile, cancellationToken);
        if (result.IsFailure)
            return Result.Failure<UserProfileDto>(result.Error);

        return Result.Success(result.Value);
    }
}
