using MediatR;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Domain.Tenants.Enums;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Security;

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 更新租户认证信息命令处理器。
/// </summary>
public sealed class UpdateTenantVerificationCommandHandler(
    ITenantRepository tenantRepository,
    ICurrentUserAccessor currentUserAccessor)
    : IRequestHandler<UpdateTenantVerificationCommand>
{
    /// <inheritdoc />
    public async Task Handle(UpdateTenantVerificationCommand request, CancellationToken cancellationToken)
    {
        // 1. 解析租户 ID
        if (!long.TryParse(request.TenantId, out var tenantId) || tenantId <= 0)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "租户 ID 无效");
        }

        // 2. 获取认证资料（带跟踪）
        var verification = await tenantRepository.GetVerificationForUpdateAsync(tenantId, cancellationToken);
        if (verification is null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "租户认证资料不存在");
        }

        // 3. 更新认证信息
        if (request.VerificationStatus.HasValue)
        {
            verification.Status = request.VerificationStatus.Value;

            // 4. 如果状态变更为已审核，记录审核信息
            if (request.VerificationStatus.Value == TenantVerificationStatus.Approved)
            {
                verification.ReviewedAt = DateTime.UtcNow;
                verification.ReviewedBy = currentUserAccessor.UserId;
            }
        }

        verification.BusinessLicenseNumber = request.BusinessLicenseNumber?.Trim();
        verification.BusinessLicenseUrl = request.BusinessLicenseUrl?.Trim();
        verification.LegalPersonName = request.LegalPersonName?.Trim();
        verification.LegalPersonIdNumber = request.LegalPersonIdNumber?.Trim();
        verification.LegalPersonIdFrontUrl = request.LegalPersonIdFrontUrl?.Trim();
        verification.LegalPersonIdBackUrl = request.LegalPersonIdBackUrl?.Trim();
        verification.BankAccountName = request.BankAccountName?.Trim();
        verification.BankAccountNumber = request.BankAccountNumber?.Trim();
        verification.BankName = request.BankName?.Trim();
        verification.AdditionalDataJson = request.AdditionalDataJson?.Trim();
        verification.ReviewRemarks = request.ReviewRemarks?.Trim();

        // 5. 保存变更
        await tenantRepository.SaveChangesAsync(cancellationToken);
    }
}
