using MediatR;
using TakeoutSaaS.Application.App.Merchants.Queries;
using TakeoutSaaS.Domain.Merchants.Repositories;
using TakeoutSaaS.Domain.Merchants.Services;
using TakeoutSaaS.Domain.Stores.Repositories;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 导出商户 PDF 处理器。
/// </summary>
public sealed class ExportMerchantPdfQueryHandler(
    IMerchantRepository merchantRepository,
    IStoreRepository storeRepository,
    ITenantRepository tenantRepository,
    IMerchantExportService exportService,
    ITenantProvider tenantProvider)
    : IRequestHandler<ExportMerchantPdfQuery, byte[]>
{
    public async Task<byte[]> Handle(ExportMerchantPdfQuery request, CancellationToken cancellationToken)
    {
        var currentTenantId = tenantProvider.GetCurrentTenantId();
        var merchant = await merchantRepository.FindByIdAsync(request.MerchantId, currentTenantId, cancellationToken);

        if (merchant == null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "商户不存在");
        }

        var stores = await storeRepository.GetByMerchantIdAsync(merchant.Id, merchant.TenantId, cancellationToken);
        var auditLogs = await merchantRepository.GetAuditLogsAsync(merchant.Id, merchant.TenantId, cancellationToken);
        var tenant = await tenantRepository.FindByIdAsync(merchant.TenantId, cancellationToken);

        return await exportService.ExportToPdfAsync(merchant, tenant?.Name, stores, auditLogs, cancellationToken);
    }
}
