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

namespace Knot.Modules.Relations.Application.Contacts;

public record DeclineContactRequestCommand(Guid UserId, Guid RequestId) : ICommand<bool>;

internal sealed class DeclineContactRequestCommandHandler : ICommandHandler<DeclineContactRequestCommand, bool>
{
    private readonly IContactsDbContext _context;

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

    public async Task<Result<bool>> Handle(DeclineContactRequestCommand request, CancellationToken cancellationToken)
    {
        var contact = await _context.Contacts.FirstOrDefaultAsync(c => c.Id == request.RequestId, cancellationToken);
        
        // Allow BOTH receiver (to decline) AND sender (to cancel)
        if (contact == null || (contact.ContactId != request.UserId && contact.UserId != request.UserId))
        {
            return Result.Failure<bool>(new Error("Contacts.NotFound", "Contact request not found or you don't have permission."));
        }

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

        return Result.Success(true);
    }
}
