using MediatR;
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.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Ids;
using TakeoutSaaS.Shared.Abstractions.Security;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 处理证照上传。
/// </summary>
public sealed class AddMerchantDocumentCommandHandler(
    IMerchantRepository merchantRepository,
    ITenantProvider tenantProvider,
    IIdGenerator idGenerator,
    ICurrentUserAccessor currentUserAccessor)
    : IRequestHandler<AddMerchantDocumentCommand, MerchantDocumentDto>
{
    /// <summary>
    /// 处理上传商户证照请求。
    /// </summary>
    /// <param name="request">上传命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>证照 DTO。</returns>
    public async Task<MerchantDocumentDto> Handle(AddMerchantDocumentCommand request, CancellationToken cancellationToken)
    {
        // 1. 获取租户并查询商户
        var tenantId = tenantProvider.GetCurrentTenantId();
        var merchant = await merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "商户不存在");

        // 2. 构建证照记录
        var document = new MerchantDocument
        {
            Id = idGenerator.NextId(),
            MerchantId = merchant.Id,
            DocumentType = request.DocumentType,
            Status = MerchantDocumentStatus.Pending,
            FileUrl = request.FileUrl.Trim(),
            DocumentNumber = request.DocumentNumber?.Trim(),
            IssuedAt = request.IssuedAt,
            ExpiresAt = request.ExpiresAt
        };

        // 3. 持久化与审计
        await merchantRepository.AddDocumentAsync(document, cancellationToken);
        await merchantRepository.AddAuditLogAsync(new MerchantAuditLog
        {
            TenantId = tenantId,
            MerchantId = merchant.Id,
            Action = MerchantAuditAction.DocumentUploaded,
            Title = "上传证照",
            Description = $"类型：{request.DocumentType}",
            OperatorId = ResolveOperatorId(),
            OperatorName = ResolveOperatorName()
        }, cancellationToken);

        await merchantRepository.SaveChangesAsync(cancellationToken);

        // 4. 返回 DTO
        return MerchantMapping.ToDto(document);
    }

    private long? ResolveOperatorId()
    {
        var id = currentUserAccessor.UserId;
        return id == 0 ? null : id;
    }

    private string ResolveOperatorName()
    {
        var id = currentUserAccessor.UserId;
        return id == 0 ? "system" : $"user:{id}";
    }
}
