using MediatR;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Application.App.Stores.Queries;
using TakeoutSaaS.Domain.Stores.Repositories;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 自提档期列表查询处理器。
/// </summary>
public sealed class ListStorePickupSlotsQueryHandler(
    IStoreRepository storeRepository)
    : IRequestHandler<ListStorePickupSlotsQuery, IReadOnlyList<StorePickupSlotDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<StorePickupSlotDto>> Handle(ListStorePickupSlotsQuery request, CancellationToken cancellationToken)
    {
        // 1. 读取门店并解析租户
        var store = await storeRepository.FindByIdAsync(request.StoreId, tenantId: null, cancellationToken);
        if (store is null)
        {
            return [];
        }
        var tenantId = store.TenantId;

        // 2. (空行后) 查询档期列表
        var slots = await storeRepository.GetPickupSlotsAsync(request.StoreId, tenantId, cancellationToken);
        return slots
            .Select(x => new StorePickupSlotDto
            {
                Id = x.Id,
                StoreId = x.StoreId,
                Name = x.Name,
                StartTime = x.StartTime,
                EndTime = x.EndTime,
                CutoffMinutes = x.CutoffMinutes,
                Capacity = x.Capacity,
                ReservedCount = x.ReservedCount,
                Weekdays = x.Weekdays,
                IsEnabled = x.IsEnabled
            })
            .ToList();
    }
}
