/**
 * @ai-summary Resend inbound email client for webhook verification and email parsing
 * @ai-context Verifies Resend webhook signatures via Svix, fetches raw emails, parses with mailparser
 */

import { Webhook } from 'svix';
import { simpleParser } from 'mailparser';
import { logger } from '../../../core/logging/logger';
import type { ResendWebhookEvent } from '../domain/email-ingestion.types';

export interface ParsedEmailResult {
  text: string | null;
  html: string | null;
  attachments: ParsedEmailAttachment[];
}

export interface ParsedEmailAttachment {
  filename: string;
  contentType: string;
  content: Buffer;
  size: number;
}

export class ResendInboundClient {
  private webhookSecret: string | undefined;
  private apiKey: string;

  constructor() {
    this.apiKey = process.env['RESEND_API_KEY'] || '';
    this.webhookSecret = process.env['RESEND_WEBHOOK_SECRET'];
  }

  /**
   * Verify Resend webhook signature using Svix
   * @throws Error if signature is invalid or secret is not configured
   */
  verifyWebhookSignature(rawBody: string | Buffer, headers: Record<string, string>): ResendWebhookEvent {
    if (!this.webhookSecret) {
      throw new Error('RESEND_WEBHOOK_SECRET is not configured');
    }

    const wh = new Webhook(this.webhookSecret);
    const verified = wh.verify(
      typeof rawBody === 'string' ? rawBody : rawBody.toString(),
      {
        'svix-id': headers['svix-id'] || '',
        'svix-timestamp': headers['svix-timestamp'] || '',
        'svix-signature': headers['svix-signature'] || '',
      }
    );

    return verified as unknown as ResendWebhookEvent;
  }

  /**
   * Fetch email metadata from Resend API including raw download URL
   */
  async getEmail(emailId: string): Promise<{ downloadUrl: string }> {
    const response = await fetch(`https://api.resend.com/emails/${emailId}`, {
      headers: { 'Authorization': `Bearer ${this.apiKey}` },
    });

    if (!response.ok) {
      throw new Error(`Failed to fetch email ${emailId}: ${response.status} ${response.statusText}`);
    }

    const data = await response.json() as { raw?: { download_url?: string } };
    const downloadUrl = data.raw?.download_url;

    if (!downloadUrl) {
      throw new Error(`No download URL for email ${emailId}`);
    }

    logger.info('Fetched email metadata from Resend', { emailId });
    return { downloadUrl };
  }

  /**
   * Download raw RFC 5322 email content from Resend download URL
   */
  async downloadRawEmail(downloadUrl: string): Promise<string> {
    const response = await fetch(downloadUrl);

    if (!response.ok) {
      throw new Error(`Failed to download raw email: ${response.status} ${response.statusText}`);
    }

    const rawEmail = await response.text();
    logger.info('Downloaded raw email', { size: rawEmail.length });
    return rawEmail;
  }

  /**
   * Parse raw RFC 5322 email into structured text/html body and attachments
   */
  async parseEmail(rawEmail: string): Promise<ParsedEmailResult> {
    const parsed = await simpleParser(rawEmail);

    return {
      text: parsed.text || null,
      html: typeof parsed.html === 'string' ? parsed.html : null,
      attachments: (parsed.attachments || []).map((att) => ({
        filename: att.filename || 'unnamed',
        contentType: att.contentType || 'application/octet-stream',
        content: att.content,
        size: att.size,
      })),
    };
  }
}
