using Knot.Modules.Relations.Domain;
using System;
using System.Threading;
using System.Threading.Tasks;
using Knot.Shared.Kernel;
using Knot.Modules.Relations.Application.Abstractions;
using Microsoft.EntityFrameworkCore;

namespace Knot.Modules.Relations.Application.Contacts;

public record AcceptContactRequestCommand(Guid UserId, Guid ContactId) : ICommand<Guid>;

internal sealed class AcceptContactRequestCommandHandler : ICommandHandler<AcceptContactRequestCommand, Guid>
{
    private readonly IContactsDbContext _context;

    public AcceptContactRequestCommandHandler(IContactsDbContext context)
    {
        _context = context;
    }

    public async Task<Result<Guid>> Handle(AcceptContactRequestCommand request, CancellationToken cancellationToken)
    {
        var contact = await _context.Contacts.FirstOrDefaultAsync(c => c.Id == request.ContactId, cancellationToken);
        if (contact == null || contact.ContactId != request.UserId)
        {
            return Result.Failure<Guid>(new Error("Contacts.NotFound", "Contact request not found."));
        }

        contact.Accept();
        await _context.SaveChangesAsync(cancellationToken);

        return Result.Success(contact.Id);
    }
}
