// Email Delivery Service for Reports
// Integrates with Abacus AI notification system for rich HTML email delivery

import {
  generateReportEmail,
  generateExecutiveSummaryEmail,
  generateAlertEmail,
  generateScheduleConfirmationEmail,
  generateDigestEmail,
  type EmailContext,
  type SummaryMetric,
} from './email-templates';
import type { ReportColumn } from './report-definitions';

const NOTIFICATION_API_URL = 'https://api.abacusai.app/api/v0/sendNotificationEmail';

interface EmailRecipient {
  email: string;
  name?: string;
}

interface ReportEmailOptions {
  recipients: EmailRecipient[];
  ccRecipients?: EmailRecipient[];
  reportName: string;
  reportDescription?: string;
  scheduleName?: string;
  periodLabel?: string;
  summaryMetrics?: SummaryMetric[];
  tableData?: {
    columns: ReportColumn[];
    rows: Record<string, unknown>[];
  };
  chartImageUrl?: string;
  detailLink?: string;
  format?: 'standard' | 'executive' | 'digest';
  highlights?: string[];
  alerts?: { severity: 'critical' | 'warning' | 'info'; message: string }[];
}

interface SendEmailResult {
  success: boolean;
  messageId?: string;
  error?: string;
}

// Send email using Abacus AI notification system
async function sendEmail(
  to: string,
  subject: string,
  htmlContent: string
): Promise<SendEmailResult> {
  const apiKey = process.env.ABACUSAI_API_KEY;
  const webAppId = process.env.WEB_APP_ID;
  const notifId = process.env.NOTIF_ID_REPORT_DELIVERY;

  if (!apiKey || !webAppId) {
    console.warn('Email delivery not configured: Missing ABACUSAI_API_KEY or WEB_APP_ID');
    return { success: false, error: 'Email not configured' };
  }

  try {
    const response = await fetch(NOTIFICATION_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        api_key: apiKey,
        web_app_id: webAppId,
        notification_id: notifId,
        recipients: [to],
        subject: subject,
        body: htmlContent,
        is_html: true,
      }),
    });

    if (response.ok) {
      const data = await response.json();
      return { success: true, messageId: data.message_id };
    } else {
      const errorText = await response.text();
      console.error('Email send failed:', errorText);
      return { success: false, error: errorText };
    }
  } catch (error) {
    console.error('Email send error:', error);
    return { success: false, error: String(error) };
  }
}

// Send report email to recipients
export async function sendReportEmail(options: ReportEmailOptions): Promise<SendEmailResult[]> {
  const results: SendEmailResult[] = [];
  const context: EmailContext = {
    reportName: options.reportName,
    reportDescription: options.reportDescription,
    generatedAt: new Date(),
    scheduleName: options.scheduleName,
    periodLabel: options.periodLabel,
    summaryMetrics: options.summaryMetrics,
    tableData: options.tableData,
    chartImageUrl: options.chartImageUrl,
    detailLink: options.detailLink,
    unsubscribeLink: options.detailLink ? `${options.detailLink.split('/admin')[0]}/admin/reports` : undefined,
  };

  let htmlContent: string;

  switch (options.format) {
    case 'executive':
      htmlContent = generateExecutiveSummaryEmail({
        ...context,
        highlights: options.highlights,
        alerts: options.alerts,
      });
      break;
    case 'digest':
      // For digest format, we'd need multiple reports - this is a fallback
      htmlContent = generateReportEmail(context);
      break;
    default:
      htmlContent = generateReportEmail(context);
  }

  const subject = `📊 ${options.reportName}${options.periodLabel ? ` - ${options.periodLabel}` : ''}`;

  // Send to all recipients
  for (const recipient of options.recipients) {
    const result = await sendEmail(recipient.email, subject, htmlContent);
    results.push(result);
  }

  // Send to CC recipients
  if (options.ccRecipients) {
    for (const recipient of options.ccRecipients) {
      const result = await sendEmail(recipient.email, `[CC] ${subject}`, htmlContent);
      results.push(result);
    }
  }

  return results;
}

// Send schedule confirmation email
export async function sendScheduleConfirmationEmail(
  recipientEmail: string,
  reportName: string,
  frequency: string,
  nextRunAt: Date,
  detailLink?: string
): Promise<SendEmailResult> {
  const context: EmailContext & { frequency: string; nextRunAt: Date } = {
    reportName,
    generatedAt: new Date(),
    frequency,
    nextRunAt,
    detailLink,
  };

  const htmlContent = generateScheduleConfirmationEmail(context);
  const subject = `✅ Report Scheduled: ${reportName}`;

  return sendEmail(recipientEmail, subject, htmlContent);
}

// Send alert email
export async function sendAlertEmail(
  recipientEmail: string,
  alertType: 'critical' | 'warning' | 'info',
  reportName: string,
  alertMessage: string,
  options?: {
    actionRequired?: string;
    summaryMetrics?: SummaryMetric[];
    detailLink?: string;
  }
): Promise<SendEmailResult> {
  const context = {
    reportName,
    generatedAt: new Date(),
    alertType,
    alertMessage,
    actionRequired: options?.actionRequired,
    summaryMetrics: options?.summaryMetrics,
    detailLink: options?.detailLink,
  };

  const htmlContent = generateAlertEmail(context);
  
  const emoji = alertType === 'critical' ? '🚨' : alertType === 'warning' ? '⚠️' : 'ℹ️';
  const subject = `${emoji} ${reportName}`;

  return sendEmail(recipientEmail, subject, htmlContent);
}

// Send digest email with multiple reports
export async function sendDigestEmail(
  recipientEmail: string,
  digestName: string,
  reports: { name: string; summary: string; link: string }[],
  periodLabel?: string
): Promise<SendEmailResult> {
  const context = {
    reportName: digestName,
    generatedAt: new Date(),
    periodLabel,
    reports,
  };

  const htmlContent = generateDigestEmail(context);
  const subject = `📊 ${digestName}${periodLabel ? ` - ${periodLabel}` : ''}`;

  return sendEmail(recipientEmail, subject, htmlContent);
}

// Helper to extract summary metrics from report data
export function extractSummaryMetrics(
  reportData: {
    totals?: Record<string, number>;
    priorTotals?: Record<string, number>;
  },
  metricConfigs: {
    key: string;
    label: string;
    format?: 'number' | 'currency' | 'percentage';
    color?: 'cyan' | 'green' | 'red' | 'amber' | 'purple';
  }[]
): SummaryMetric[] {
  const metrics: SummaryMetric[] = [];

  for (const config of metricConfigs) {
    const value = reportData.totals?.[config.key];
    if (value !== undefined) {
      const metric: SummaryMetric = {
        label: config.label,
        value,
        format: config.format,
        color: config.color,
      };

      // Calculate change if prior totals available
      const priorValue = reportData.priorTotals?.[config.key];
      if (priorValue !== undefined && priorValue !== 0) {
        metric.change = ((value - priorValue) / priorValue) * 100;
        metric.changeLabel = 'vs prior period';
      }

      metrics.push(metric);
    }
  }

  return metrics;
}

// Format period label from date range
export function formatPeriodLabel(startDate?: Date, endDate?: Date, frequency?: string): string {
  const now = new Date();
  
  if (startDate && endDate) {
    const startStr = startDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
    const endStr = endDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
    return `${startStr} - ${endStr}`;
  }

  switch (frequency) {
    case 'daily':
      return now.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' });
    case 'weekly':
      const weekStart = new Date(now);
      weekStart.setDate(now.getDate() - now.getDay());
      const weekEnd = new Date(weekStart);
      weekEnd.setDate(weekStart.getDate() + 6);
      return `Week of ${weekStart.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`;
    case 'monthly':
      return now.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
    case 'quarterly':
      const quarter = Math.floor(now.getMonth() / 3) + 1;
      return `Q${quarter} ${now.getFullYear()}`;
    case 'yearly':
      return `Year ${now.getFullYear()}`;
    default:
      return now.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
  }
}

// ============================================
// ADDITIONAL FUNCTIONS FOR API ROUTES
// ============================================

import type { AlertEmailData, ExecutiveBriefData } from './email-templates';
import { BRAND } from '@/lib/white-label/constants';

// Send executive brief email
export async function sendExecutiveBriefEmail(
  recipients: string[],
  briefData: ExecutiveBriefData
): Promise<SendEmailResult> {
  const briefDateStr = briefData.briefDate.toLocaleDateString('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  });

  const highlights = briefData.highlights || [];
  const alerts = briefData.anomalies?.map(a => ({
    severity: a.severity as 'critical' | 'warning' | 'info',
    message: a.description,
  })) || [];

  const context = {
    reportName: 'Weekly Intelligence Brief',
    generatedAt: briefData.briefDate,
    periodLabel: briefDateStr,
    highlights,
    alerts,
    summaryMetrics: briefData.operationsHealth?.map(oh => ({
      label: oh.metric,
      value: oh.value,
      color: (oh.status === 'good' ? 'green' : oh.status === 'warning' ? 'amber' : 'red') as 'cyan' | 'green' | 'red' | 'amber' | 'purple',
    })),
  };

  const htmlContent = generateExecutiveSummaryEmail(context);
  const subject = `📊 Weekly Intelligence Brief - ${briefDateStr}`;

  const results: SendEmailResult[] = [];
  for (const recipient of recipients) {
    const result = await sendEmail(recipient, subject, htmlContent);
    results.push(result);
  }

  return {
    success: results.every(r => r.success),
    error: results.find(r => r.error)?.error,
  };
}

// Test email delivery
export async function testEmailDelivery(recipient: string): Promise<SendEmailResult> {
  const testContext: EmailContext = {
    reportName: 'Test Email Delivery',
    reportDescription: 'This is a test email to verify email delivery is working correctly.',
    generatedAt: new Date(),
    summaryMetrics: [
      { label: 'Test Metric 1', value: 12345, format: 'number', color: 'cyan' },
      { label: 'Test Metric 2', value: 98765, format: 'currency', color: 'green' },
      { label: 'Test Metric 3', value: 87.5, format: 'percentage', color: 'purple' },
    ],
  };

  const htmlContent = generateReportEmail(testContext);
  const subject = `✅ Test Email - ${BRAND.companyName}`;

  return sendEmail(recipient, subject, htmlContent);
}

// Deliver scheduled report (simplified interface for API)
export async function deliverScheduledReport(
  recipients: string[],
  reportName: string,
  reportDescription: string | undefined,
  data: Record<string, unknown>[],
  columns: Array<{ key: string; label: string; type?: string }>,
  options?: {
    summary?: Record<string, unknown>;
    periodLabel?: string;
    detailLink?: string;
  }
): Promise<SendEmailResult> {
  // Convert columns to ReportColumn format
  const reportColumns = columns.map(c => ({
    key: c.key,
    label: c.label,
    type: (c.type || 'string') as 'string' | 'number' | 'currency' | 'date' | 'percentage' | 'boolean' | 'status',
    format: c.type,
  }));

  // Extract summary metrics from options.summary
  const summaryMetrics: SummaryMetric[] = [];
  if (options?.summary) {
    for (const [key, value] of Object.entries(options.summary)) {
      if (typeof value === 'number') {
        summaryMetrics.push({
          label: key.replace(/_/g, ' ').replace(/^(total|avg)/, '').trim(),
          value,
          format: key.includes('currency') ? 'currency' : 'number',
          color: 'cyan',
        });
      }
    }
  }

  const context: EmailContext = {
    reportName,
    reportDescription,
    generatedAt: new Date(),
    periodLabel: options?.periodLabel,
    summaryMetrics: summaryMetrics.length > 0 ? summaryMetrics : undefined,
    tableData: data.length > 0 ? { columns: reportColumns, rows: data.slice(0, 10) } : undefined,
    detailLink: options?.detailLink,
  };

  const htmlContent = generateReportEmail(context);
  const subject = `📊 ${reportName}${options?.periodLabel ? ` - ${options.periodLabel}` : ''}`;

  const results: SendEmailResult[] = [];
  for (const recipient of recipients) {
    const result = await sendEmail(recipient, subject, htmlContent);
    results.push(result);
  }

  return {
    success: results.every(r => r.success),
    error: results.find(r => r.error)?.error,
  };
}
