using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Merchants.Commands;
using TakeoutSaaS.Domain.Merchants.Entities;
using TakeoutSaaS.Domain.Merchants.Enums;
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 UnfreezeMerchantCommandHandler(
    IMerchantRepository merchantRepository,
    ICurrentUserAccessor currentUserAccessor,
    ILogger<UnfreezeMerchantCommandHandler> logger)
    : IRequestHandler<UnfreezeMerchantCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(UnfreezeMerchantCommand 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. 检查是否已解冻
        if (!merchant.IsFrozen)
        {
            throw new BusinessException(ErrorCodes.ValidationFailed, "商户未处于冻结状态");
        }

        // 4. 执行解冻
        var actorId = currentUserAccessor.UserId == 0 ? (long?)null : currentUserAccessor.UserId;
        var actorName = currentUserAccessor.IsAuthenticated ? $"user:{currentUserAccessor.UserId}" : "system";

        merchant.IsFrozen = false;
        merchant.FrozenReason = null;
        merchant.FrozenAt = null;
        merchant.RowVersion = request.RowVersion;

        // 5. 记录审核日志
        await merchantRepository.AddAuditLogAsync(new MerchantAuditLog
        {
            TenantId = merchant.TenantId,
            MerchantId = merchant.Id,
            Action = MerchantAuditAction.Unfrozen,
            Title = "商户解冻",
            Description = "管理员解冻商户",
            OperatorId = actorId,
            OperatorName = actorName
        }, cancellationToken);

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

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

        logger.LogInformation("解冻商户 {MerchantId}", merchant.Id);
        return true;
    }

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