using MediatR;
using SocialService.Domain.AggregatesModel.RelationshipAggregate;

namespace SocialService.API.Application.Queries;

/// <summary>
/// EN: Handler for GetAllRelationshipsQuery.
/// VI: Handler cho GetAllRelationshipsQuery.
/// </summary>
public class GetAllRelationshipsQueryHandler : IRequestHandler<GetAllRelationshipsQuery, GetAllRelationshipsResult>
{
    private readonly IRelationshipRepository _relationshipRepository;

    public GetAllRelationshipsQueryHandler(IRelationshipRepository relationshipRepository)
    {
        _relationshipRepository = relationshipRepository;
    }

    public async Task<GetAllRelationshipsResult> Handle(GetAllRelationshipsQuery request, CancellationToken cancellationToken)
    {
        // EN: Parse filters
        // VI: Parse các filter
        int? statusId = request.StatusFilter?.ToLower() switch
        {
            "pending" => RelationshipStatus.Pending.Id,
            "accepted" => RelationshipStatus.Accepted.Id,
            "rejected" => RelationshipStatus.Rejected.Id,
            "cancelled" => RelationshipStatus.Cancelled.Id,
            _ => null
        };

        int? typeId = request.TypeFilter?.ToLower() switch
        {
            "friendship" => RelationshipType.Friendship.Id,
            "following" => RelationshipType.Following.Id,
            _ => null
        };

        var relationships = await _relationshipRepository.GetAllAsync(request.Skip, request.Take, statusId, typeId);
        var totalCount = await _relationshipRepository.GetTotalCountAsync(statusId, typeId);

        var dtos = relationships.Select(r => new RelationshipAdminDto(
            r.Id,
            r.RequesterId,
            r.AddresseeId,
            r.Type.Name,
            r.Status.Name,
            r.CreatedAt,
            r.UpdatedAt));

        return new GetAllRelationshipsResult(dtos, totalCount);
    }
}
