using Knot.Shared.Kernel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Knot.Modules.Relations.Application.Abstractions;
using Knot.Modules.Relations.Domain;
using Knot.Contracts.Relations.Application.Contacts;

namespace Knot.Modules.Relations.Application.Contacts;

internal sealed class CheckBlockedStatusQueryHandler : IQueryHandler<CheckBlockedStatusQuery, List<Guid>>
{
    private readonly IContactsDbContext _context;

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

    public async Task<Result<List<Guid>>> Handle(CheckBlockedStatusQuery request, CancellationToken cancellationToken)
    {
        // Find which candidate IDs are in a "Blocked" relationship with the current user.
        // We check both directions (currentUser blocks candidate OR candidate blocks currentUser).
        var blockedIds = await _context.Contacts
            .Where(c => (c.UserId == request.UserId || c.ContactId == request.UserId) 
                        && c.Status == ContactStatus.Blocked
                        && (request.CandidateIds.Contains(c.UserId) || request.CandidateIds.Contains(c.ContactId)))
            .Select(c => c.UserId == request.UserId ? c.ContactId : c.UserId)
            .ToListAsync(cancellationToken);

        return Result.Success(blockedIds);
    }
}
