using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Merchants.Commands;
using TakeoutSaaS.Domain.Merchants.Entities;
using TakeoutSaaS.Domain.Merchants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Security;

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 更新商户经营模式命令处理器。
/// </summary>
public sealed class UpdateMerchantOperatingModeCommandHandler(
    IMerchantRepository merchantRepository,
    ICurrentUserAccessor currentUserAccessor,
    ILogger<UpdateMerchantOperatingModeCommandHandler> logger)
    : IRequestHandler<UpdateMerchantOperatingModeCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(UpdateMerchantOperatingModeCommand request, CancellationToken cancellationToken)
    {
        // 1. 验证 RowVersion
        if (request.RowVersion == 0)
        {
            throw new BusinessException(ErrorCodes.ValidationFailed, "RowVersion 不能为空");
        }

        // 2. 读取商户信息
        var merchant = await merchantRepository.FindByIdAsync(request.MerchantId, cancellationToken);
        if (merchant == null)
        {
            return false;
        }

        // 3. 记录变更日志
        var actorId = currentUserAccessor.UserId == 0 ? (long?)null : currentUserAccessor.UserId;
        var actorName = currentUserAccessor.IsAuthenticated ? $"user:{currentUserAccessor.UserId}" : "system";
        var oldValue = merchant.OperatingMode?.ToString();
        var newValue = request.OperatingMode.ToString();

        if (!string.Equals(oldValue, newValue, StringComparison.Ordinal))
        {
            await merchantRepository.AddChangeLogAsync(new MerchantChangeLog
            {
                TenantId = merchant.TenantId,
                MerchantId = merchant.Id,
                FieldName = "operatingMode",
                OldValue = oldValue,
                NewValue = newValue,
                ChangedBy = actorId,
                ChangedByName = actorName,
                ChangeType = "Update"
            }, cancellationToken);
        }

        // 4. 更新经营模式
        merchant.OperatingMode = request.OperatingMode;
        merchant.RowVersion = request.RowVersion;

        // 5. 持久化
        await merchantRepository.UpdateMerchantAsync(merchant, cancellationToken);

        try
        {
            await merchantRepository.SaveChangesAsync(cancellationToken);
        }
        catch (Exception exception) when (IsConcurrencyException(exception))
        {
            throw new BusinessException(ErrorCodes.Conflict, "商户信息已被修改，请刷新后重试");
        }

        logger.LogInformation("更新商户 {MerchantId} 经营模式为 {OperatingMode}", merchant.Id, request.OperatingMode);
        return true;
    }

    private static bool IsConcurrencyException(Exception exception)
        => string.Equals(exception.GetType().Name, "DbUpdateConcurrencyException", StringComparison.Ordinal);
}
