/**
 * Queue Message Interfaces
 * 
 * Defines the structure of messages sent to and received from SQS queues
 */

import { QueueType, JobStatus } from '../constants/queue.constants';
import { InvoiceContextEnum } from 'src/common/enum/invoice-context.enum';

/**
 * Base interface for all queue messages
 */
export interface BaseQueueMessage {
  messageId?: string; // SQS Message ID (set by SQS)
  queueType: QueueType; // Type of queue (communication or heavy-processing)
  subType: string; // Sub-type: email, whatsapp, sms (communication) or invoice (heavy-processing)
  timestamp: string; // ISO timestamp when message was created
  attemptCount?: number; // Number of processing attempts
  correlationId?: string; // For tracking related messages
  userId?: string; // User who triggered the action
  metadata?: Record<string, any>; // Any additional context
}

/**
 * Email queue message payload
 */
export interface EmailQueueMessage extends BaseQueueMessage {
  queueType: 'communication';
  subType: 'email';
  data: {
    to: {
      emailAddress: string;
      name?: string;
    };
    from: {
      address: string;
      name: string;
    };
    subject: string;
    htmlBody?: string;
    textBody?: string;
    templateKey?: string; // Reference to email template
    templateData?: Record<string, any>; // Data to populate template
    cc?: Array<{ emailAddress: string; name?: string }>;
    bcc?: Array<{ emailAddress: string; name?: string }>;
    attachments?: Array<{
      name: string;
      /**
       * Base64 encoded content (for small attachments only).
       * For large files like PDFs, prefer using S3 metadata fields
       * to avoid hitting SQS 256 KB message size limits.
       */
      content?: string;
      /**
       * S3 object key for the attachment. When provided, the actual file
       * will be downloaded from S3 just before sending the email.
       */
      s3Key?: string;
      /**
       * Optional S3 bucket override. If not provided, the default
       * application bucket will be used.
       */
      s3Bucket?: string;
      contentType: string;
    }>;
    replyTo?: { emailAddress: string; name?: string };
  };
}

/**
 * Bulk email queue message payload — a single provider-side batch (ZeptoMail /batch)
 * carrying many recipients, each with its own merge data and (optional) registrationId
 * for per-recipient tracking. `from`, `subject` and `templateKey` are shared across the
 * batch; `metadata.templateId` / `metadata.createdBy` drive tracking.
 */
export interface BulkEmailQueueMessage extends BaseQueueMessage {
  queueType: 'communication';
  subType: 'bulk-email';
  data: {
    from: {
      address: string;
      name: string;
    };
    subject: string;
    templateKey?: string;
    recipients: Array<{
      emailAddress: string;
      name?: string;
      templateData?: Record<string, any>;
      registrationId?: number;
    }>;
    /**
     * Batch-level attachments applied to every recipient, carried as S3 references only —
     * BulkEmailProcessor downloads them before sending. Never inline bytes: a bulk message already
     * holds a whole chunk of recipients, leaving no room under the 256 KB SQS limit.
     */
    attachments?: Array<{
      name: string;
      s3Key: string;
      contentType: string;
      s3Bucket?: string;
    }>;
  };
}

/**
 * WhatsApp queue message payload
 */
export interface WhatsAppQueueMessage extends BaseQueueMessage {
  queueType: 'communication';
  subType: 'whatsapp';
  data: {
    phoneNumber: string; // With country code
    templateName: string; // WATI template name
    parameters?: Array<{
      name: string;
      value: string;
    }>;
    broadcastName?: string; // For broadcast messages
  };
}

/**
 * Bulk WhatsApp queue message payload — one WATI bulk template send for many recipients.
 */
export interface BulkWhatsAppQueueMessage extends BaseQueueMessage {
  queueType: 'communication';
  subType: 'bulk-whatsapp';
  data: {
    templateName: string;
    broadcastName: string;
    recipients: Array<{
      whatsappNumber: string;
      customParams?: Array<{ name: string; value: string }>;
      registrationId?: number;
    }>;
    globalParameters?: Array<{ name: string; value: string }>;
  };
}

/**
 * SMS queue message payload
 */
export interface SmsQueueMessage extends BaseQueueMessage {
  queueType: 'communication';
  subType: 'sms';
  data: {
    phoneNumber: string; // With country code
    message: string;
    senderId?: string; // SMS sender ID
    dltTemplateId?: string; // DLT template ID for India
    unicode?: boolean; // Whether message contains unicode characters
  };
}

/**
 * Invoice generation queue message payload
 * 
 * Context:
 * - 'regular': Generates post-payment invoice (invoice type online/offline determined from payment mode)
 * - 'proforma': Generates pre-payment proforma invoice for blessed seekers
 */
export interface InvoiceQueueMessage extends BaseQueueMessage {
  queueType: 'heavy-processing';
  subType: 'invoice';
  data: {
    registrationId: number;
    userId?: number;
    invoiceContext: InvoiceContextEnum;
    sendEmail?: boolean; // Whether to send email after generation (default: true)
    sendWhatsApp?: boolean; // Whether to send WhatsApp after generation (only for proforma)
  };
}

/** Scheduled bulk join-link generation for a program session. */
export interface JoinLinkGenerationQueueMessage extends BaseQueueMessage {
  queueType: 'event';
  subType: 'join-link-generation';
  data: {
    programSessionId: number;
    /** Attendee (default) or Panelist. */
    role?: string;
    batchSize?: number;
    actorUserId?: number;
  };
}

/** Scheduled program-level session communication (Welcome / Program completion). */
export interface SessionCommunicationTriggerQueueMessage extends BaseQueueMessage {
  queueType: 'event';
  subType: 'session-communication-trigger';
  data: {
    programId: number;
    /** WELCOME or PROGRAM_COMPLETION. */
    purpose: string;
    actorUserId?: number;
  };
}

/**
 * Union type for all queue messages
 */
export type QueueMessage =
  | EmailQueueMessage
  | BulkEmailQueueMessage
  | WhatsAppQueueMessage
  | BulkWhatsAppQueueMessage
  | SmsQueueMessage
  | InvoiceQueueMessage
  | JoinLinkGenerationQueueMessage
  | SessionCommunicationTriggerQueueMessage;

/**
 * SQS Message wrapper (what we receive from SQS)
 */
export interface SqsMessageWrapper {
  MessageId: string;
  ReceiptHandle: string;
  Body: string; // JSON stringified QueueMessage
  Attributes?: Record<string, any>;
  MessageAttributes?: Record<string, any>;
  MD5OfBody?: string;
}

/**
 * Queue processing result
 */
export interface QueueProcessingResult {
  success: boolean;
  messageId: string;
  queueType: QueueType;
  processingTimeMs: number;
  error?: {
    code: string;
    message: string;
    stack?: string;
    retryable: boolean;
  };
}

/**
 * Queue metrics for monitoring
 */
export interface QueueMetrics {
  queueType: QueueType;
  messagesProcessed: number;
  messagesSucceeded: number;
  messagesFailed: number;
  averageProcessingTimeMs: number;
  lastProcessedAt?: string;
}
