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;

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 导出商户 PDF 处理器。
/// </summary>
public sealed class ExportMerchantPdfQueryHandler(
    IMerchantRepository merchantRepository,
    IStoreRepository storeRepository,
    ITenantRepository tenantRepository,
    IMerchantExportService exportService)
    : IRequestHandler<ExportMerchantPdfQuery, byte[]>
{
    public async Task<byte[]> Handle(ExportMerchantPdfQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询商户（跨租户）
        var merchant = await merchantRepository.FindByIdAsync(request.MerchantId, cancellationToken);
        if (merchant == null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "商户不存在");
        }

        // 2. (空行后) 查询关联数据
        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);

        // 3. (空行后) 导出 PDF
        return await exportService.ExportToPdfAsync(merchant, tenant?.Name, stores, auditLogs, cancellationToken);
    }
}
