// EN: Query to get per-shop stats for current merchant.
// VI: Query để lấy thống kê từng shop của merchant hiện tại.

using MediatR;
using MerchantService.Domain.AggregatesModel.MerchantAggregate;
using MerchantService.Domain.AggregatesModel.ShopAggregate;
using MerchantService.Domain.Exceptions;

namespace MerchantService.API.Application.Queries.Shops;

/// <summary>
/// EN: Query to get per-shop stats for current merchant.
/// VI: Query để lấy thống kê từng shop của merchant hiện tại.
/// </summary>
public record GetShopStatsQuery(Guid UserId) : IRequest<IReadOnlyList<ShopStatsDto>>;

/// <summary>
/// EN: Per-shop stats DTO with placeholder values.
/// VI: DTO thống kê từng shop với giá trị placeholder.
/// </summary>
public record ShopStatsDto
{
    public Guid ShopId { get; init; }
    public int ProductCount { get; init; }
    public int OrderCount { get; init; }
    public int StaffCount { get; init; }
    public decimal Revenue { get; init; }
}

/// <summary>
/// EN: Handler for getting per-shop stats.
/// VI: Handler để lấy thống kê từng shop.
/// </summary>
public class GetShopStatsQueryHandler : IRequestHandler<GetShopStatsQuery, IReadOnlyList<ShopStatsDto>>
{
    private readonly IMerchantRepository _merchantRepository;
    private readonly IShopRepository _shopRepository;

    public GetShopStatsQueryHandler(
        IMerchantRepository merchantRepository,
        IShopRepository shopRepository)
    {
        _merchantRepository = merchantRepository;
        _shopRepository = shopRepository;
    }

    public async Task<IReadOnlyList<ShopStatsDto>> Handle(GetShopStatsQuery request, CancellationToken cancellationToken)
    {
        // EN: Use user ID passed from the controller
        // VI: Dùng user ID được truyền từ controller
        var merchant = await _merchantRepository.GetByUserIdAsync(request.UserId, cancellationToken);
        if (merchant == null)
        {
            return [];
        }

        var shops = await _shopRepository.GetByMerchantIdAsync(merchant.Id, cancellationToken);

        // EN: Return placeholder stats (0 values) — cross-service aggregation needs event-driven approach.
        // VI: Trả về stats placeholder (giá trị 0) — aggregation đa dịch vụ cần event-driven.
        return shops.Select(s => new ShopStatsDto
        {
            ShopId = s.Id,
            ProductCount = 0,
            OrderCount = 0,
            StaffCount = 0,
            Revenue = 0
        }).ToList();
    }
}
