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.Enums;
using TakeoutSaaS.Domain.Merchants.Repositories;
using TakeoutSaaS.Domain.Stores.Repositories;
using TakeoutSaaS.Domain.Tenants.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 UpdateMerchantCommandHandler(
    IMerchantRepository merchantRepository,
    IStoreRepository storeRepository,
    ITenantRepository tenantRepository,
    ICurrentUserAccessor currentUserAccessor,
    ILogger<UpdateMerchantCommandHandler> logger)
    : IRequestHandler<UpdateMerchantCommand, UpdateMerchantResultDto?>
{
    /// <inheritdoc />
    public async Task<UpdateMerchantResultDto?> Handle(UpdateMerchantCommand request, CancellationToken cancellationToken)
    {
        if (request.RowVersion == null || request.RowVersion.Length == 0)
        {
            throw new BusinessException(ErrorCodes.ValidationFailed, "RowVersion 不能为空");
        }

        // 1. 读取商户信息（跨租户）
        var merchant = await merchantRepository.FindByIdAsync(request.MerchantId, cancellationToken);

        if (merchant == null)
        {
            return null;
        }

        // 2. (空行后) 规范化输入
        var name = NormalizeRequired(request.Name, "商户名称");
        var contactPhone = NormalizeRequired(request.ContactPhone, "联系电话");
        var licenseNumber = NormalizeOptional(request.LicenseNumber);
        var legalRepresentative = NormalizeOptional(request.LegalRepresentative);
        var registeredAddress = NormalizeOptional(request.RegisteredAddress);
        var contactEmail = NormalizeOptional(request.ContactEmail);

        var now = DateTime.UtcNow;
        var actorId = currentUserAccessor.UserId == 0 ? (long?)null : currentUserAccessor.UserId;
        var actorName = ResolveActorName();
        var changes = new List<MerchantChangeLog>();
        var criticalChanged = false;

        TrackChange("name", merchant.BrandName, name, isCritical: true);
        TrackChange("licenseNumber", merchant.BusinessLicenseNumber, licenseNumber, isCritical: true);
        TrackChange("legalRepresentative", merchant.LegalPerson, legalRepresentative, isCritical: true);
        TrackChange("registeredAddress", merchant.Address, registeredAddress, isCritical: true);
        TrackChange("contactPhone", merchant.ContactPhone, contactPhone, isCritical: false);
        TrackChange("contactEmail", merchant.ContactEmail, contactEmail, isCritical: false);

        // 3. (空行后) 写入字段
        merchant.BrandName = name;
        merchant.BusinessLicenseNumber = licenseNumber;
        merchant.LegalPerson = legalRepresentative;
        merchant.Address = registeredAddress;
        merchant.ContactPhone = contactPhone;
        merchant.ContactEmail = contactEmail;
        merchant.RowVersion = request.RowVersion;

        var requiresReview = merchant.Status == MerchantStatus.Approved && criticalChanged;
        if (requiresReview)
        {
            merchant.Status = MerchantStatus.Pending;
            merchant.IsFrozen = true;
            merchant.FrozenReason = "关键信息变更待审核";
            merchant.FrozenAt = now;
        }
        else if (merchant.Status == MerchantStatus.Rejected)
        {
            merchant.Status = MerchantStatus.Pending;
            merchant.IsFrozen = false;
            merchant.FrozenReason = null;
            merchant.FrozenAt = null;
        }

        // 4. (空行后) 持久化日志与数据
        await merchantRepository.UpdateMerchantAsync(merchant, cancellationToken);
        foreach (var log in changes)
        {
            await merchantRepository.AddChangeLogAsync(log, cancellationToken);
        }

        if (requiresReview)
        {
            await merchantRepository.AddAuditLogAsync(new MerchantAuditLog
            {
                TenantId = merchant.TenantId,
                MerchantId = merchant.Id,
                Action = MerchantAuditAction.ReviewPendingReApproval,
                Title = "关键信息变更待审核",
                Description = "关键信息修改后已进入待审核状态",
                OperatorId = actorId,
                OperatorName = actorName
            }, cancellationToken);
        }

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

        logger.LogInformation("更新商户 {MerchantId} - {Name}", merchant.Id, merchant.BrandName);

        // 5. (空行后) 返回更新结果
        var stores = await storeRepository.GetByMerchantIdAsync(merchant.Id, merchant.TenantId, cancellationToken);
        var tenant = await tenantRepository.FindByIdAsync(merchant.TenantId, cancellationToken);
        var detail = MerchantMapping.ToDetailDto(merchant, tenant?.Name, MerchantMapping.ToStoreDtos(stores));

        return new UpdateMerchantResultDto
        {
            Merchant = detail,
            RequiresReview = requiresReview
        };

        void TrackChange(string fieldName, string? oldValue, string? newValue, bool isCritical)
        {
            var normalizedOld = NormalizeOptional(oldValue);
            var normalizedNew = NormalizeOptional(newValue);
            if (string.Equals(normalizedOld, normalizedNew, StringComparison.Ordinal))
            {
                return;
            }

            if (isCritical)
            {
                criticalChanged = true;
            }

            changes.Add(new MerchantChangeLog
            {
                TenantId = merchant.TenantId,
                MerchantId = merchant.Id,
                FieldName = fieldName,
                OldValue = normalizedOld,
                NewValue = normalizedNew,
                ChangedBy = actorId,
                ChangedByName = actorName,
                ChangeType = "Update"
            });
        }
    }

    private static string NormalizeRequired(string? value, string fieldName)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            throw new BusinessException(ErrorCodes.ValidationFailed, $"{fieldName}不能为空");
        }

        return value.Trim();
    }

    private static string? NormalizeOptional(string? value)
        => string.IsNullOrWhiteSpace(value) ? null : value.Trim();

    private string ResolveActorName()
        => currentUserAccessor.IsAuthenticated ? $"user:{currentUserAccessor.UserId}" : "system";

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