using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Merchants.Commands;
using TakeoutSaaS.Application.App.Merchants.Dto;
using TakeoutSaaS.Domain.Merchants.Entities;
using TakeoutSaaS.Domain.Merchants.Repositories;

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 创建商户命令处理器。
/// </summary>
public sealed class CreateMerchantCommandHandler(IMerchantRepository merchantRepository, ILogger<CreateMerchantCommandHandler> logger)
    : IRequestHandler<CreateMerchantCommand, MerchantDto>
{
    /// <inheritdoc />
    public async Task<MerchantDto> Handle(CreateMerchantCommand request, CancellationToken cancellationToken)
    {
        // 1. 构建商户实体
        var merchant = new Merchant
        {
            BrandName = request.BrandName.Trim(),
            BrandAlias = request.BrandAlias?.Trim(),
            LogoUrl = request.LogoUrl?.Trim(),
            Category = request.Category?.Trim(),
            ContactPhone = request.ContactPhone.Trim(),
            ContactEmail = request.ContactEmail?.Trim(),
            Status = request.Status,
            JoinedAt = DateTime.UtcNow
        };

        // 2. 持久化
        await merchantRepository.AddMerchantAsync(merchant, cancellationToken);
        await merchantRepository.SaveChangesAsync(cancellationToken);

        // 3. 记录日志
        logger.LogInformation("创建商户 {MerchantId} - {BrandName}", merchant.Id, merchant.BrandName);
        return MapToDto(merchant);
    }

    private static MerchantDto MapToDto(Merchant merchant) => new()
    {
        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
    };
}
