using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Knot.Contracts.Relations.Application.Abstractions;
using Knot.Contracts.Relations.Domain;
using Knot.Modules.Relations.Domain;
using Knot.Modules.Relations.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;

namespace Knot.Modules.Relations.Application.Abstractions;

internal sealed class FriendshipRepository : IFriendshipRepository
{
    private readonly RelationsDbContext _context;

    public FriendshipRepository(RelationsDbContext context)
    {
        _context = context;
    }

    public async Task<List<Knot.Contracts.Relations.Domain.Friendship>> GetAcceptedFriendshipsAsync(Guid userId, CancellationToken ct = default)
    {
        var contacts = await _context.Contacts
            .Where(f => f.Status == ContactStatus.Accepted && (f.UserId == userId || f.ContactId == userId))
            .ToListAsync(ct);

        return contacts.Select(f => new Knot.Contracts.Relations.Domain.Friendship(
            f.Id,
            f.UserId,
            f.ContactId,
            (Knot.Contracts.Relations.Domain.FriendshipStatus)f.Status,
            f.CreatedAt
        )).ToList();
    }
}
