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

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 门店员工列表查询处理器。
/// </summary>
public sealed class ListStoreStaffQueryHandler(
    IMerchantRepository merchantRepository,
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<ListStoreStaffQuery, IReadOnlyList<StoreStaffDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<StoreStaffDto>> Handle(ListStoreStaffQuery request, CancellationToken cancellationToken)
    {
        // 1. 校验门店存在
        var tenantId = tenantProvider.GetCurrentTenantId();
        var store = await storeRepository.FindByIdAsync(request.StoreId, tenantId, cancellationToken);
        if (store is null)
        {
            return [];
        }

        // 2. 查询员工
        var staffs = await merchantRepository.GetStaffByStoreAsync(request.StoreId, tenantId, cancellationToken);

        if (request.RoleType.HasValue)
        {
            staffs = staffs.Where(x => x.RoleType == request.RoleType.Value).ToList();
        }

        if (request.Status.HasValue)
        {
            staffs = staffs.Where(x => x.Status == request.Status.Value).ToList();
        }

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