using System.Linq;
using MediatR;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Application.App.Stores.Queries;
using TakeoutSaaS.Domain.Stores.Repositories;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 排班列表查询处理器。
/// </summary>
public sealed class ListStoreEmployeeShiftsQueryHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<ListStoreEmployeeShiftsQuery, IReadOnlyList<StoreEmployeeShiftDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<StoreEmployeeShiftDto>> Handle(ListStoreEmployeeShiftsQuery request, CancellationToken cancellationToken)
    {
        // 1. 时间范围
        var from = request.From ?? DateTime.UtcNow.Date;
        var to = request.To ?? from.AddDays(7);
        var tenantId = tenantProvider.GetCurrentTenantId();

        // 2. 查询排班
        var shifts = await storeRepository.GetShiftsAsync(request.StoreId, tenantId, from, to, cancellationToken);

        if (request.StaffId.HasValue)
        {
            shifts = shifts.Where(x => x.StaffId == request.StaffId.Value).ToList();
        }

        // 3. 映射 DTO
        return shifts.Select(StoreMapping.ToDto).ToList();
    }
}
