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

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 实名资料提交流程。
/// </summary>
public sealed class SubmitTenantVerificationCommandHandler(
    ITenantRepository tenantRepository,
    IIdGenerator idGenerator)
    : IRequestHandler<SubmitTenantVerificationCommand, TenantVerificationDto>
{
    /// <inheritdoc />
    public async Task<TenantVerificationDto> Handle(SubmitTenantVerificationCommand request, CancellationToken cancellationToken)
    {
        // 1. 获取租户
        var tenant = await tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "租户不存在");

        // 2. 读取或初始化实名资料
        var profile = await tenantRepository.GetVerificationProfileAsync(request.TenantId, cancellationToken)
                       ?? new TenantVerificationProfile { Id = idGenerator.NextId(), TenantId = tenant.Id };

        // 3. 填充资料
        profile.BusinessLicenseNumber = request.BusinessLicenseNumber;
        profile.BusinessLicenseUrl = request.BusinessLicenseUrl;
        profile.LegalPersonName = request.LegalPersonName;
        profile.LegalPersonIdNumber = request.LegalPersonIdNumber;
        profile.LegalPersonIdFrontUrl = request.LegalPersonIdFrontUrl;
        profile.LegalPersonIdBackUrl = request.LegalPersonIdBackUrl;
        profile.BankAccountName = request.BankAccountName;
        profile.BankAccountNumber = request.BankAccountNumber;
        profile.BankName = request.BankName;
        profile.AdditionalDataJson = request.AdditionalDataJson;
        profile.Status = TenantVerificationStatus.Pending;
        profile.SubmittedAt = DateTime.UtcNow;
        profile.ReviewedAt = null;
        profile.ReviewRemarks = null;
        profile.ReviewedBy = null;
        profile.ReviewedByName = null;

        // 4. 保存资料并记录审计
        await tenantRepository.UpsertVerificationProfileAsync(profile, cancellationToken);
        await tenantRepository.AddAuditLogAsync(new TenantAuditLog
        {
            TenantId = tenant.Id,
            Action = TenantAuditAction.VerificationSubmitted,
            Title = "提交实名认证资料",
            Description = request.BusinessLicenseNumber
        }, cancellationToken);
        await tenantRepository.SaveChangesAsync(cancellationToken);

        // 5. 返回 DTO
        return profile.ToVerificationDto()
               ?? throw new BusinessException(ErrorCodes.InternalServerError, "实名资料保存失败");
    }
}
