/**
 * WhatsApp Business Cloud API Type Definitions
 *
 * Provides TypeScript types for WhatsApp integration
 * Based on Meta Cloud API v21.0 specification
 */

// ============================================================================
// API Request/Response Types
// ============================================================================

/**
 * WhatsApp message type
 * Supports text, template, and interactive messages
 */
export interface WhatsAppMessage {
  /** Recipient phone number (international format without +) */
  to: string;
  /** Message type */
  type: 'text' | 'template' | 'interactive' | 'image' | 'video' | 'document';
  /** Text message content */
  text?: {
    body: string;
    preview_url?: boolean;
  };
  /** Template message (for approved templates) */
  template?: {
    name: string;
    language: {
      code: string;
    };
    components?: Array<{
      type: string;
      parameters: Array<{
        type: string;
        text: string;
      }>;
    }>;
  };
  /** Interactive message (buttons, lists) */
  interactive?: {
    type: 'button' | 'list';
    header?: {
      type: 'text';
      text: string;
    };
    body: {
      text: string;
    };
    footer?: {
      text: string;
    };
    action: {
      buttons?: Array<{
        type: 'reply';
        reply: {
          id: string;
          title: string;
        };
      }>;
      button?: string;
      sections?: Array<{
        title: string;
        rows: Array<{
          id: string;
          title: string;
          description?: string;
        }>;
      }>;
    };
  };
}

/**
 * Meta webhook payload structure
 * Received when customer sends message or status changes
 */
export interface WhatsAppWebhookPayload {
  object: 'whatsapp_business_account';
  entry: Array<{
    id: string;
    changes: Array<{
      value: {
        messaging_product: 'whatsapp';
        metadata: {
          display_phone_number: string;
          phone_number_id: string;
        };
        contacts?: Array<{
          profile: {
            name: string;
          };
          wa_id: string;
        }>;
        messages?: Array<WhatsAppIncomingMessage>;
        statuses?: Array<WhatsAppMessageStatus>;
        errors?: Array<WhatsAppError>;
      };
      field: 'messages';
    }>;
  }>;
}

/**
 * Incoming message from customer
 */
export interface WhatsAppIncomingMessage {
  from: string;
  id: string;
  timestamp: string;
  type: 'text' | 'image' | 'video' | 'document' | 'audio' | 'interactive' | 'button';
  text?: {
    body: string;
  };
  image?: {
    id: string;
    mime_type: string;
    sha256: string;
  };
  video?: {
    id: string;
    mime_type: string;
    sha256: string;
  };
  document?: {
    id: string;
    mime_type: string;
    sha256: string;
    filename?: string;
  };
  audio?: {
    id: string;
    mime_type: string;
    sha256: string;
  };
  interactive?: {
    type: 'button_reply' | 'list_reply';
    button_reply?: {
      id: string;
      title: string;
    };
    list_reply?: {
      id: string;
      title: string;
      description?: string;
    };
  };
  button?: {
    text: string;
    payload: string;
  };
  context?: {
    from: string;
    id: string;
  };
}

/**
 * Message delivery status update
 */
export interface WhatsAppMessageStatus {
  id: string;
  status: 'sent' | 'delivered' | 'read' | 'failed';
  timestamp: string;
  recipient_id: string;
  conversation?: {
    id: string;
    origin: {
      type: string;
    };
  };
  pricing?: {
    billable: boolean;
    pricing_model: string;
    category: string;
  };
  errors?: Array<WhatsAppError>;
}

/**
 * WhatsApp API error
 */
export interface WhatsAppError {
  code: number;
  title: string;
  message: string;
  error_data?: {
    details: string;
  };
}

// ============================================================================
// Service Response Types
// ============================================================================

/**
 * Send message response from service
 */
export interface SendMessageResponse {
  success: boolean;
  messageId?: string;
  error?: string;
}

/**
 * Webhook verification result
 */
export interface WebhookVerificationResult {
  isValid: boolean;
  challenge?: string;
  error?: string;
}

/**
 * Connection status from service
 */
export interface WhatsAppConnectionStatus {
  connected: boolean;
  phoneNumber?: string;
  displayPhoneNumber?: string;
  verifiedName?: string;
  connectedAt?: Date;
}

// ============================================================================
// API Endpoint Request/Response Types
// ============================================================================

/**
 * Connect endpoint request body
 */
export interface ConnectWhatsAppRequest {
  phone_number_id: string;
  access_token: string;
}

/**
 * Connect endpoint response
 */
export interface ConnectWhatsAppResponse {
  success: boolean;
  message?: string;
  error?: string;
}

/**
 * Disconnect endpoint response
 */
export interface DisconnectWhatsAppResponse {
  success: boolean;
  message?: string;
  error?: string;
}

/**
 * Status endpoint response
 */
export interface WhatsAppStatusResponse {
  connected: boolean;
  phone_number?: string;
  display_phone_number?: string;
  verified_name?: string;
  connected_at?: string;
  error?: string;
}

// ============================================================================
// N8N Integration Types
// ============================================================================

/**
 * Payload forwarded to N8N webhook
 */
export interface N8NWhatsAppPayload {
  platform: 'whatsapp';
  user_id: string;
  customer_phone: string;
  customer_name: string;
  message: {
    id: string;
    timestamp: string;
    type: string;
    text: string;
  };
  metadata: {
    phone_number_id: string;
    display_phone_number: string;
  };
}

// ============================================================================
// Meta API Response Types
// ============================================================================

/**
 * Meta API send message response
 */
export interface MetaSendMessageResponse {
  messaging_product: 'whatsapp';
  contacts: Array<{
    input: string;
    wa_id: string;
  }>;
  messages: Array<{
    id: string;
  }>;
}

/**
 * Meta API phone number info response
 */
export interface MetaPhoneNumberInfo {
  verified_name: string;
  display_phone_number: string;
  quality_rating: 'GREEN' | 'YELLOW' | 'RED' | 'UNKNOWN';
  id: string;
}

/**
 * Meta API error response
 */
export interface MetaErrorResponse {
  error: {
    message: string;
    type: string;
    code: number;
    error_subcode?: number;
    fbtrace_id: string;
  };
}

// ============================================================================
// Database Types (matching Prisma schema)
// ============================================================================

/**
 * User WhatsApp connection fields
 */
export interface UserWhatsAppFields {
  whatsappConnected: boolean;
  whatsappNumber: string | null;
  whatsappConnectedAt: Date | null;
}

/**
 * Stored WhatsApp credentials (encrypted)
 */
export interface StoredWhatsAppCredentials {
  phoneNumberId: string;
  accessToken: string; // Decrypted
}

// ============================================================================
// Configuration Types
// ============================================================================

/**
 * WhatsApp service configuration
 */
export interface WhatsAppServiceConfig {
  /** Meta API version */
  apiVersion: string;
  /** Meta API base URL */
  apiBaseUrl: string;
  /** Webhook verify token */
  verifyToken: string;
  /** App secret for signature verification */
  appSecret: string;
  /** N8N webhook URL for forwarding messages */
  n8nWebhookUrl?: string;
  /** N8N authentication token */
  n8nAuthToken?: string;
}

// ============================================================================
// Utility Types
// ============================================================================

/**
 * Type guard for WhatsApp webhook payload
 */
export function isWhatsAppWebhookPayload(
  payload: unknown
): payload is WhatsAppWebhookPayload {
  return (
    typeof payload === 'object' &&
    payload !== null &&
    'object' in payload &&
    (payload as WhatsAppWebhookPayload).object === 'whatsapp_business_account'
  );
}

/**
 * Type guard for text message
 */
export function isTextMessage(
  message: WhatsAppIncomingMessage
): message is WhatsAppIncomingMessage & { text: { body: string } } {
  return message.type === 'text' && message.text !== undefined;
}

/**
 * Type guard for interactive message
 */
export function isInteractiveMessage(
  message: WhatsAppIncomingMessage
): message is WhatsAppIncomingMessage & { interactive: NonNullable<WhatsAppIncomingMessage['interactive']> } {
  return message.type === 'interactive' && message.interactive !== undefined;
}

// ============================================================================
// Constants
// ============================================================================

/**
 * WhatsApp message types
 */
export const WHATSAPP_MESSAGE_TYPES = [
  'text',
  'image',
  'video',
  'document',
  'audio',
  'interactive',
  'button',
  'template',
] as const;

/**
 * WhatsApp message statuses
 */
export const WHATSAPP_MESSAGE_STATUSES = [
  'sent',
  'delivered',
  'read',
  'failed',
] as const;

/**
 * WhatsApp interactive types
 */
export const WHATSAPP_INTERACTIVE_TYPES = ['button', 'list'] as const;

/**
 * Meta API version
 */
export const META_API_VERSION = 'v21.0';

/**
 * Meta API base URL
 */
export const META_API_BASE_URL = `https://graph.facebook.com/${META_API_VERSION}`;
