using System;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Knot.Shared.Kernel;
using Knot.Contracts.Auth.Domain;
using Knot.Contracts.Settings.Application.Abstractions;
using Knot.Contracts.Settings.Application.DTOs;
using System.Linq;

namespace Host.Application.Federation.Commands;

public record ResolveUserResponse(Guid Id, string Username, string DisplayName, string? Avatar);
public record ResolveUserCommand(string Username) : ICommand<ResolveUserResponse>;

internal sealed class ResolveUserCommandHandler : ICommandHandler<ResolveUserCommand, ResolveUserResponse>
{
    private readonly IUserRepository _userRepository;

    public ResolveUserCommandHandler(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }

    public async Task<Result<ResolveUserResponse>> Handle(ResolveUserCommand request, CancellationToken cancellationToken)
    {
        var user = await _userRepository.GetByUsernameAsync(request.Username, cancellationToken);
        
        if (user == null || user.IsExternal)
        {
            return Result.Failure<ResolveUserResponse>(new Error("Federation.UserNotFound", "User not found on this server."));
        }

        return Result.Success(new ResolveUserResponse(
            user.Id,
            user.Username,
            user.DisplayName,
            user.Avatar
        ));
    }
}

