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

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 门店详情查询处理器。
/// </summary>
public sealed class GetStoreByIdQueryHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetStoreByIdQuery, StoreDto?>
{
    private readonly IStoreRepository _storeRepository = storeRepository;
    private readonly ITenantProvider _tenantProvider = tenantProvider;

    /// <inheritdoc />
    public async Task<StoreDto?> Handle(GetStoreByIdQuery request, CancellationToken cancellationToken)
    {
        var tenantId = _tenantProvider.GetCurrentTenantId();
        var store = await _storeRepository.FindByIdAsync(request.StoreId, tenantId, cancellationToken);
        return store == null ? null : MapToDto(store);
    }

    private static StoreDto MapToDto(Store store) => new()
    {
        Id = store.Id,
        TenantId = store.TenantId,
        MerchantId = store.MerchantId,
        Code = store.Code,
        Name = store.Name,
        Phone = store.Phone,
        ManagerName = store.ManagerName,
        Status = store.Status,
        Province = store.Province,
        City = store.City,
        District = store.District,
        Address = store.Address,
        Longitude = store.Longitude,
        Latitude = store.Latitude,
        Announcement = store.Announcement,
        Tags = store.Tags,
        DeliveryRadiusKm = store.DeliveryRadiusKm,
        SupportsDineIn = store.SupportsDineIn,
        SupportsPickup = store.SupportsPickup,
        SupportsDelivery = store.SupportsDelivery,
        SupportsReservation = store.SupportsReservation,
        SupportsQueueing = store.SupportsQueueing,
        CreatedAt = store.CreatedAt
    };
}
