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

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 获取商户详情查询处理器。
/// </summary>
public sealed class GetMerchantByIdQueryHandler(IMerchantRepository merchantRepository, ITenantProvider tenantProvider)
    : IRequestHandler<GetMerchantByIdQuery, MerchantDto?>
{
    /// <inheritdoc />
    public async Task<MerchantDto?> Handle(GetMerchantByIdQuery request, CancellationToken cancellationToken)
    {
        // 1. 获取租户上下文
        var tenantId = tenantProvider.GetCurrentTenantId();
        var merchant = await merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken);
        if (merchant == null)
        {
            return null;
        }

        // 2. 返回 DTO
        return new MerchantDto
        {
            Id = merchant.Id,
            TenantId = merchant.TenantId,
            BrandName = merchant.BrandName,
            BrandAlias = merchant.BrandAlias,
            LogoUrl = merchant.LogoUrl,
            Category = merchant.Category,
            ContactPhone = merchant.ContactPhone,
            ContactEmail = merchant.ContactEmail,
            Status = merchant.Status,
            JoinedAt = merchant.JoinedAt,
            CreatedAt = merchant.CreatedAt
        };
    }
}
