using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Merchants.Commands;
using TakeoutSaaS.Application.App.Merchants.Dto;
using TakeoutSaaS.Domain.Merchants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 更新商户命令处理器。
/// </summary>
public sealed class UpdateMerchantCommandHandler(
    IMerchantRepository merchantRepository,
    ITenantProvider tenantProvider,
    ILogger<UpdateMerchantCommandHandler> logger)
    : IRequestHandler<UpdateMerchantCommand, MerchantDto?>
{
    /// <inheritdoc />
    public async Task<MerchantDto?> Handle(UpdateMerchantCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取现有商户
        var tenantId = tenantProvider.GetCurrentTenantId();
        var existing = await merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken);
        if (existing == null)
        {
            return null;
        }

        // 2. 更新字段
        existing.BrandName = request.BrandName.Trim();
        existing.BrandAlias = request.BrandAlias?.Trim();
        existing.LogoUrl = request.LogoUrl?.Trim();
        existing.Category = request.Category?.Trim();
        existing.ContactPhone = request.ContactPhone.Trim();
        existing.ContactEmail = request.ContactEmail?.Trim();
        existing.Status = request.Status;

        // 3. 持久化
        await merchantRepository.UpdateMerchantAsync(existing, cancellationToken);
        await merchantRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("更新商户 {MerchantId} - {BrandName}", existing.Id, existing.BrandName);

        // 4. 返回 DTO
        return MapToDto(existing);
    }

    private static MerchantDto MapToDto(Domain.Merchants.Entities.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
    };
}
