'use strict';

const { sanitizePayload } = require('../../modules/billing/billing.httpProvider');
const { createMicfdiRealStampVerifier } = require('../../modules/billing/micfdiRealStampAuthorization');

function safeProviderResponse(value = {}) {
  const safe = sanitizePayload(value || {});
  return {
    success: safe?.success,
    code: safe?.code,
    message: safe?.message,
  };
}

function outcomeFromError(authorization, error) {
  return {
    attemptId: authorization?.attemptId || null,
    status: error.fiscalStatus || 'failed_before_pac_call',
    pac_called: Boolean(error.pacCalled),
    endpoint_usado: 'global',
    esglobal: true,
    xml_present: false,
    pdf_present: false,
    provider_response_sanitized: safeProviderResponse(error.providerResponse),
    error_code: String(error.code || 'micfdi_real_stamp_failed'),
    manual_review_required: Boolean(error.manualReviewRequired),
    reported_at: new Date().toISOString(),
  };
}

async function execute(command, config = {}, deps = {}) {
  const verifier = deps.micfdiRealStampVerifier || createMicfdiRealStampVerifier();
  let authorization;
  try {
    authorization = await verifier.verifyAndConsume(command, config);
  } catch (error) {
    error.outcome = outcomeFromError(command?.payload?.authorization_payload, error);
    throw error;
  }
  const fiscalPayload = command.payload?.fiscal_payload || {};

  if (command.payload?.dry_run) {
    return {
      ok: true,
      dryRun: true,
      route: 'cloud_to_agent',
      authorization_signature_validated: true,
      agent_would_call_pac: false,
      pac_called: false,
      endpoint_resolved: 'global',
      esglobal: true,
      max_per_run: 1,
      attemptId: authorization.attemptId,
      payload_prepared: sanitizePayload(fiscalPayload),
    };
  }

  const service = deps.billingService || require('../../modules/billing/billing.service');
  const tenantContext = {
    tenantId: authorization.tenantId,
    branchId: authorization.branchId,
    realStampAuthorization: authorization,
  };
  try {
    const invoice = await service.createGlobalInvoice(
      tenantContext,
      fiscalPayload,
      { realStampAuthorization: authorization }
    );
    const xmlPresent = Boolean(invoice.xml_base64 || invoice.xml_url_or_path);
    const pdfPresent = Boolean(invoice.pdf_base64 || invoice.pdf_url_or_path);
    if (!invoice.uuid || !xmlPresent || !pdfPresent) {
      const error = new Error('micfdi_real_stamp_incomplete_persisted_result');
      error.code = 'micfdi_real_stamp_incomplete_persisted_result';
      error.pacCalled = true;
      error.fiscalStatus = 'failed_after_pac_call';
      error.manualReviewRequired = true;
      error.providerResponse = invoice.provider_response;
      throw error;
    }
    return {
      ok: true,
      outcome: {
        attemptId: authorization.attemptId,
        status: 'completed',
        pac_called: true,
        endpoint_usado: 'global',
        esglobal: true,
        uuid: invoice.uuid || null,
        serie: invoice.serie || null,
        folio: invoice.folio || null,
        xml_present: xmlPresent,
        pdf_present: pdfPresent,
        provider_response_sanitized: safeProviderResponse(invoice.provider_response),
        error_code: null,
        manual_review_required: false,
        reported_at: new Date().toISOString(),
      },
    };
  } catch (error) {
    error.outcome = outcomeFromError(authorization, error);
    throw error;
  }
}

module.exports = { execute, outcomeFromError, safeProviderResponse };
