// EN: Query to get shop settings (features, operating hours).
// VI: Query để lấy cài đặt shop (tính năng, giờ hoạt động).

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

namespace MerchantService.API.Application.Queries.Shops;

/// <summary>
/// EN: Query to get shop settings by shop ID.
/// VI: Query để lấy cài đặt shop theo shop ID.
/// </summary>
public record GetShopSettingsQuery(Guid ShopId) : IRequest<ShopSettingsDto?>;

/// <summary>
/// EN: Shop settings DTO with feature flags and operating hours.
/// VI: DTO cài đặt shop với feature flags và giờ hoạt động.
/// </summary>
public record ShopSettingsDto
{
    public Guid ShopId { get; init; }
    public ShopFeaturesDto Features { get; init; } = new();
    public string? OpenTime { get; init; }
    public string? CloseTime { get; init; }
    public List<string> OpenDays { get; init; } = [];
}

/// <summary>
/// EN: Shop features DTO.
/// VI: DTO tính năng shop.
/// </summary>
public record ShopFeaturesDto
{
    public bool HasInventory { get; init; }
    public bool HasBooking { get; init; }
    public bool HasTables { get; init; }
    public bool HasKitchen { get; init; }
    public bool HasShipping { get; init; }
    public bool HasDelivery { get; init; }
}

/// <summary>
/// EN: Handler for getting shop settings.
/// VI: Handler để lấy cài đặt shop.
/// </summary>
public class GetShopSettingsQueryHandler : IRequestHandler<GetShopSettingsQuery, ShopSettingsDto?>
{
    private readonly IShopRepository _shopRepository;

    public GetShopSettingsQueryHandler(IShopRepository shopRepository)
    {
        _shopRepository = shopRepository;
    }

    public async Task<ShopSettingsDto?> Handle(GetShopSettingsQuery request, CancellationToken cancellationToken)
    {
        var shop = await _shopRepository.GetByIdAsync(request.ShopId, cancellationToken);
        if (shop == null)
        {
            return null;
        }

        return new ShopSettingsDto
        {
            ShopId = shop.Id,
            Features = new ShopFeaturesDto
            {
                HasInventory = shop.Features.HasInventory,
                HasBooking = shop.Features.HasBooking,
                HasTables = shop.Features.HasTables,
                HasKitchen = shop.Features.HasKitchen,
                HasShipping = shop.Features.HasShipping,
                HasDelivery = shop.Features.HasDelivery
            },
            OpenTime = shop.OperatingHours?.OpenTime.ToString("HH:mm"),
            CloseTime = shop.OperatingHours?.CloseTime.ToString("HH:mm"),
            OpenDays = shop.OperatingHours?.OpenDays?.Select(d => d.ToString()).ToList() ?? []
        };
    }
}
