using MediatR;
using TakeoutSaaS.Application.App.Stores;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Application.App.Stores.Queries;
using TakeoutSaaS.Domain.Stores.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 门店资质列表查询处理器。
/// </summary>
public sealed class ListStoreQualificationsQueryHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<ListStoreQualificationsQuery, IReadOnlyList<StoreQualificationDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<StoreQualificationDto>> Handle(ListStoreQualificationsQuery request, CancellationToken cancellationToken)
    {
        // 1. 校验门店存在
        var tenantId = tenantProvider.GetCurrentTenantId();
        var store = await storeRepository.FindByIdAsync(request.StoreId, tenantId, cancellationToken);
        if (store is null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "门店不存在");
        }

        // 2. (空行后) 读取资质列表
        var qualifications = await storeRepository.GetQualificationsAsync(request.StoreId, tenantId, cancellationToken);

        // 3. (空行后) 映射 DTO
        return qualifications.Select(StoreMapping.ToDto).ToList();
    }
}
