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 RemoveContactCommand(Guid UserId, Guid ContactRelationId) : ICommand;

internal sealed class RemoveContactCommandHandler : ICommandHandler<RemoveContactCommand>
{
    private readonly IContactsDbContext _context;

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

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

        if (contact.UserId != request.UserId && contact.ContactId != request.UserId)
        {
            return Result.Failure(new Error("Contacts.Unauthorized", "You are not authorized to remove this contact."));
        }

        _context.Contacts.Remove(contact);
        await _context.SaveChangesAsync(cancellationToken);

        return Result.Success();
    }
}
