/**
 * Zalo OA ZNS template configuration.
 *
 * Maps internal notification template keys to ZNS template IDs registered in
 * the Zalo OA Manager console. Template IDs must be configured via environment
 * variables (ZALO_ZNS_TEMPLATE_*).
 *
 * Template parameters must match the ZNS template definitions exactly —
 * see the Zalo OA Manager for the approved parameter names.
 */

export interface ZaloZnsTemplateConfig {
  /** ZNS template ID (registered in Zalo OA Manager) */
  templateId: string;
  /** Map our internal template data keys to ZNS parameter names */
  mapParams: (data: Record<string, unknown>) => Record<string, string>;
}

/**
 * Returns the ZNS template configurations, reading template IDs from environment.
 * Returns only templates where the env var is configured.
 */
export function getZaloZnsTemplates(): Record<string, ZaloZnsTemplateConfig> {
  const templates: Record<string, ZaloZnsTemplateConfig> = {};

  // Inquiry received — notify property owner/agent about a new inquiry
  const inquiryTplId = process.env['ZALO_ZNS_TEMPLATE_INQUIRY'] ?? '';
  if (inquiryTplId) {
    templates['inquiry.received'] = {
      templateId: inquiryTplId,
      mapParams: (data) => ({
        customer_name: String(data['senderName'] ?? ''),
        property_name: String(data['listingTitle'] ?? ''),
        message: String(data['message'] ?? ''),
      }),
    };
  }

  // Payment confirmed — notify buyer about successful payment
  const paymentTplId = process.env['ZALO_ZNS_TEMPLATE_PAYMENT'] ?? '';
  if (paymentTplId) {
    templates['payment.confirmed'] = {
      templateId: paymentTplId,
      mapParams: (data) => ({
        payment_id: String(data['paymentId'] ?? ''),
        amount: String(data['amountVND'] ?? ''),
        payment_method: String(data['provider'] ?? ''),
      }),
    };
  }

  // Listing approved — notify owner that listing is live
  const listingApprovedTplId = process.env['ZALO_ZNS_TEMPLATE_LISTING_APPROVED'] ?? '';
  if (listingApprovedTplId) {
    templates['listing.approved'] = {
      templateId: listingApprovedTplId,
      mapParams: (data) => ({
        listing_title: String(data['listingTitle'] ?? ''),
      }),
    };
  }

  // Listing rejected — notify owner that listing was rejected
  const listingRejectedTplId = process.env['ZALO_ZNS_TEMPLATE_LISTING_REJECTED'] ?? '';
  if (listingRejectedTplId) {
    templates['listing.rejected'] = {
      templateId: listingRejectedTplId,
      mapParams: (data) => ({
        listing_title: String(data['listingTitle'] ?? ''),
        reason: String(data['reason'] ?? ''),
      }),
    };
  }

  // Listing sold — notify owner that listing is sold
  const listingSoldTplId = process.env['ZALO_ZNS_TEMPLATE_LISTING_SOLD'] ?? '';
  if (listingSoldTplId) {
    templates['listing.sold'] = {
      templateId: listingSoldTplId,
      mapParams: (data) => ({
        listing_title: String(data['listingTitle'] ?? ''),
      }),
    };
  }

  return templates;
}
