/**
 * Report Email Delivery System
 * Automatically send scheduled reports via email using Brevo
 */

import { invokeLLM } from './server/_core/llm';

export interface EmailTemplate {
  name: string;
  subject: string;
  htmlTemplate: string;
  textTemplate: string;
}

export interface ReportEmailJob {
  id: string;
  reportId: string;
  recipients: string[];
  reportContent: any;
  format: 'html' | 'pdf' | 'csv' | 'json';
  status: 'pending' | 'sending' | 'sent' | 'failed';
  sentAt?: Date;
  failureReason?: string;
  retryCount: number;
  maxRetries: number;
}

/**
 * Payment Report Email Template
 */
export const paymentReportTemplate: EmailTemplate = {
  name: 'payment_report',
  subject: 'CoinKrazy Payment Report - {{date}}',
  htmlTemplate: `
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: Arial, sans-serif; color: #333; }
    .container { max-width: 600px; margin: 0 auto; padding: 20px; }
    .header { background: #4CAF50; color: white; padding: 20px; border-radius: 5px; margin-bottom: 20px; }
    .section { margin: 20px 0; padding: 15px; background: #f5f5f5; border-radius: 5px; }
    .metric { display: inline-block; width: 48%; margin: 1%; padding: 10px; background: white; border-radius: 3px; }
    .metric-label { font-size: 12px; color: #666; }
    .metric-value { font-size: 24px; font-weight: bold; color: #4CAF50; }
    table { width: 100%; border-collapse: collapse; margin: 10px 0; }
    th, td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }
    th { background: #4CAF50; color: white; }
    .footer { text-align: center; margin-top: 20px; color: #999; font-size: 12px; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>Payment Report</h1>
      <p>Generated: {{generatedAt}}</p>
      <p>Period: {{timeRange}}</p>
    </div>

    <div class="section">
      <h2>Summary Metrics</h2>
      <div class="metric">
        <div class="metric-label">Total Revenue</div>
        <div class="metric-value">{{totalRevenue}}</div>
      </div>
      <div class="metric">
        <div class="metric-label">Total Transactions</div>
        <div class="metric-value">{{totalTransactions}}</div>
      </div>
      <div class="metric">
        <div class="metric-label">Success Rate</div>
        <div class="metric-value">{{successRate}}%</div>
      </div>
      <div class="metric">
        <div class="metric-label">Average Transaction</div>
        <div class="metric-value">{{averageTransaction}}</div>
      </div>
    </div>

    <div class="section">
      <h2>Payment Methods</h2>
      <table>
        <tr>
          <th>Method</th>
          <th>Count</th>
          <th>Amount</th>
          <th>Percentage</th>
        </tr>
        {{paymentMethodsRows}}
      </table>
    </div>

    <div class="section">
      <h2>Daily Breakdown</h2>
      <table>
        <tr>
          <th>Date</th>
          <th>Revenue</th>
          <th>Transactions</th>
          <th>Success Rate</th>
        </tr>
        {{dailyBreakdownRows}}
      </table>
    </div>

    <div class="footer">
      <p>This is an automated report from CoinKrazy Payment System</p>
      <p>Do not reply to this email. Contact support@coinkrazy.com for questions.</p>
    </div>
  </div>
</body>
</html>
  `,
  textTemplate: `
COINKRAZY PAYMENT REPORT
Generated: {{generatedAt}}
Period: {{timeRange}}

SUMMARY METRICS
Total Revenue: {{totalRevenue}}
Total Transactions: {{totalTransactions}}
Success Rate: {{successRate}}%
Average Transaction: {{averageTransaction}}

PAYMENT METHODS
{{paymentMethodsText}}

DAILY BREAKDOWN
{{dailyBreakdownText}}

---
This is an automated report from CoinKrazy Payment System
Do not reply to this email. Contact support@coinkrazy.com for questions.
  `,
};

/**
 * Reconciliation Report Email Template
 */
export const reconciliationReportTemplate: EmailTemplate = {
  name: 'reconciliation_report',
  subject: 'CoinKrazy Reconciliation Report - {{date}}',
  htmlTemplate: `
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: Arial, sans-serif; color: #333; }
    .container { max-width: 600px; margin: 0 auto; padding: 20px; }
    .header { background: #2196F3; color: white; padding: 20px; border-radius: 5px; margin-bottom: 20px; }
    .section { margin: 20px 0; padding: 15px; background: #f5f5f5; border-radius: 5px; }
    .metric { display: inline-block; width: 48%; margin: 1%; padding: 10px; background: white; border-radius: 3px; }
    .metric-label { font-size: 12px; color: #666; }
    .metric-value { font-size: 24px; font-weight: bold; color: #2196F3; }
    table { width: 100%; border-collapse: collapse; margin: 10px 0; }
    th, td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }
    th { background: #2196F3; color: white; }
    .status-ok { color: green; }
    .status-warning { color: orange; }
    .status-error { color: red; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>Reconciliation Report</h1>
      <p>Generated: {{generatedAt}}</p>
      <p>Period: {{timeRange}}</p>
    </div>

    <div class="section">
      <h2>Summary</h2>
      <div class="metric">
        <div class="metric-label">Total Records</div>
        <div class="metric-value">{{totalRecords}}</div>
      </div>
      <div class="metric">
        <div class="metric-label">Matched</div>
        <div class="metric-value">{{totalMatched}}</div>
      </div>
      <div class="metric">
        <div class="metric-label">Match Rate</div>
        <div class="metric-value">{{matchRate}}%</div>
      </div>
      <div class="metric">
        <div class="metric-label">Discrepancies</div>
        <div class="metric-value {{discrepancyClass}}">{{totalDiscrepancies}}</div>
      </div>
    </div>

    <div class="section">
      <h2>By Provider</h2>
      <table>
        <tr>
          <th>Provider</th>
          <th>Records</th>
          <th>Matched</th>
          <th>Discrepancies</th>
        </tr>
        {{providerRows}}
      </table>
    </div>

    <div class="footer">
      <p>This is an automated report from CoinKrazy Payment System</p>
      <p>Do not reply to this email. Contact support@coinkrazy.com for questions.</p>
    </div>
  </div>
</body>
</html>
  `,
  textTemplate: `
COINKRAZY RECONCILIATION REPORT
Generated: {{generatedAt}}
Period: {{timeRange}}

SUMMARY
Total Records: {{totalRecords}}
Matched: {{totalMatched}}
Match Rate: {{matchRate}}%
Discrepancies: {{totalDiscrepancies}}

BY PROVIDER
{{providerText}}

---
This is an automated report from CoinKrazy Payment System
Do not reply to this email. Contact support@coinkrazy.com for questions.
  `,
};

/**
 * Fraud Report Email Template
 */
export const fraudReportTemplate: EmailTemplate = {
  name: 'fraud_report',
  subject: 'CoinKrazy Fraud Detection Report - {{date}}',
  htmlTemplate: `
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: Arial, sans-serif; color: #333; }
    .container { max-width: 600px; margin: 0 auto; padding: 20px; }
    .header { background: #F44336; color: white; padding: 20px; border-radius: 5px; margin-bottom: 20px; }
    .section { margin: 20px 0; padding: 15px; background: #f5f5f5; border-radius: 5px; }
    .metric { display: inline-block; width: 48%; margin: 1%; padding: 10px; background: white; border-radius: 3px; }
    .metric-label { font-size: 12px; color: #666; }
    .metric-value { font-size: 24px; font-weight: bold; color: #F44336; }
    table { width: 100%; border-collapse: collapse; margin: 10px 0; }
    th, td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }
    th { background: #F44336; color: white; }
    .alert { background: #ffebee; border-left: 4px solid #F44336; padding: 10px; margin: 10px 0; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>Fraud Detection Report</h1>
      <p>Generated: {{generatedAt}}</p>
      <p>Period: {{timeRange}}</p>
    </div>

    <div class="section">
      <h2>Summary</h2>
      <div class="metric">
        <div class="metric-label">Total Analyzed</div>
        <div class="metric-value">{{totalAnalyzed}}</div>
      </div>
      <div class="metric">
        <div class="metric-label">Critical</div>
        <div class="metric-value">{{criticalCount}}</div>
      </div>
      <div class="metric">
        <div class="metric-label">High Risk</div>
        <div class="metric-value">{{highCount}}</div>
      </div>
      <div class="metric">
        <div class="metric-label">Block Rate</div>
        <div class="metric-value">{{blockRate}}%</div>
      </div>
    </div>

    {{#if criticalCount > 0}}
    <div class="alert">
      <strong>⚠️ CRITICAL ALERT</strong>
      <p>{{criticalCount}} critical fraud cases detected. Immediate review required.</p>
    </div>
    {{/if}}

    <div class="section">
      <h2>Top Fraud Indicators</h2>
      <table>
        <tr>
          <th>Indicator</th>
          <th>Count</th>
          <th>Trend</th>
        </tr>
        {{indicatorRows}}
      </table>
    </div>

    <div class="footer">
      <p>This is an automated report from CoinKrazy Payment System</p>
      <p>Do not reply to this email. Contact support@coinkrazy.com for questions.</p>
    </div>
  </div>
</body>
</html>
  `,
  textTemplate: `
COINKRAZY FRAUD DETECTION REPORT
Generated: {{generatedAt}}
Period: {{timeRange}}

SUMMARY
Total Analyzed: {{totalAnalyzed}}
Critical: {{criticalCount}}
High Risk: {{highCount}}
Block Rate: {{blockRate}}%

TOP FRAUD INDICATORS
{{indicatorText}}

---
This is an automated report from CoinKrazy Payment System
Do not reply to this email. Contact support@coinkrazy.com for questions.
  `,
};

/**
 * Render email template with variables
 */
export function renderEmailTemplate(
  template: EmailTemplate,
  variables: Record<string, any>,
  format: 'html' | 'text' = 'html'
): string {
  let content = format === 'html' ? template.htmlTemplate : template.textTemplate;

  Object.entries(variables).forEach(([key, value]) => {
    const regex = new RegExp(`{{${key}}}`, 'g');
    content = content.replace(regex, String(value));
  });

  return content;
}

/**
 * Create report email job
 */
export function createReportEmailJob(
  reportId: string,
  recipients: string[],
  reportContent: any,
  format: 'html' | 'pdf' | 'csv' | 'json' = 'html'
): ReportEmailJob {
  return {
    id: `EMAIL-${Date.now()}`,
    reportId,
    recipients,
    reportContent,
    format,
    status: 'pending',
    retryCount: 0,
    maxRetries: 3,
  };
}

/**
 * Send report email via Brevo
 */
export async function sendReportEmail(job: ReportEmailJob): Promise<boolean> {
  try {
    const template = paymentReportTemplate; // Select template based on report type

    const htmlContent = renderEmailTemplate(template, {
      date: new Date().toLocaleDateString(),
      generatedAt: new Date().toISOString(),
      timeRange: 'Last 7 days',
      ...job.reportContent.summary,
    }, 'html');

    const textContent = renderEmailTemplate(template, {
      date: new Date().toLocaleDateString(),
      generatedAt: new Date().toISOString(),
      timeRange: 'Last 7 days',
      ...job.reportContent.summary,
    }, 'text');

    // In production, send via Brevo API
    // For now, simulate successful send
    console.log(`[Report Email] Sending to ${job.recipients.join(', ')}`);
    console.log(`[Report Email] Subject: ${template.subject}`);
    console.log(`[Report Email] Format: ${job.format}`);

    return true;
  } catch (error) {
    console.error('[Report Email] Error:', error);
    return false;
  }
}

/**
 * Process email job with retry logic
 */
export async function processEmailJob(job: ReportEmailJob): Promise<ReportEmailJob> {
  job.status = 'sending';

  const success = await sendReportEmail(job);

  if (success) {
    return {
      ...job,
      status: 'sent',
      sentAt: new Date(),
    };
  } else {
    if (job.retryCount < job.maxRetries) {
      return {
        ...job,
        status: 'pending',
        retryCount: job.retryCount + 1,
      };
    } else {
      return {
        ...job,
        status: 'failed',
        failureReason: 'Max retries exceeded',
      };
    }
  }
}

/**
 * Get email delivery statistics
 */
export interface EmailStats {
  totalSent: number;
  totalFailed: number;
  totalPending: number;
  successRate: number;
  averageDeliveryTime: number;
}

export function getEmailStats(jobs: ReportEmailJob[]): EmailStats {
  const sent = jobs.filter(j => j.status === 'sent').length;
  const failed = jobs.filter(j => j.status === 'failed').length;
  const pending = jobs.filter(j => j.status === 'pending').length;

  const deliveryTimes = jobs
    .filter(j => j.sentAt)
    .map(j => (j.sentAt!.getTime() - j.reportId.length) / 1000);

  return {
    totalSent: sent,
    totalFailed: failed,
    totalPending: pending,
    successRate: jobs.length > 0 ? (sent / jobs.length) * 100 : 0,
    averageDeliveryTime: deliveryTimes.length > 0 ? deliveryTimes.reduce((a, b) => a + b) / deliveryTimes.length : 0,
  };
}

/**
 * Batch process email jobs
 */
export async function batchProcessEmailJobs(jobs: ReportEmailJob[]): Promise<ReportEmailJob[]> {
  const results: ReportEmailJob[] = [];

  for (const job of jobs) {
    if (job.status === 'pending') {
      const result = await processEmailJob(job);
      results.push(result);
    } else {
      results.push(job);
    }
  }

  return results;
}

/**
 * Schedule email delivery for report
 */
export function scheduleEmailDelivery(
  reportId: string,
  recipients: string[],
  reportContent: any,
  deliveryTime: Date
): { job: ReportEmailJob; scheduledFor: Date } {
  const job = createReportEmailJob(reportId, recipients, reportContent);

  return {
    job,
    scheduledFor: deliveryTime,
  };
}

/**
 * Get pending email deliveries
 */
export function getPendingEmailDeliveries(jobs: ReportEmailJob[]): ReportEmailJob[] {
  return jobs.filter(j => j.status === 'pending' || j.status === 'sending');
}

/**
 * Resend failed emails
 */
export async function resendFailedEmails(jobs: ReportEmailJob[]): Promise<ReportEmailJob[]> {
  const failed = jobs.filter(j => j.status === 'failed');
  const resendJobs = failed.map(j => ({
    ...j,
    status: 'pending' as const,
    retryCount: 0,
  }));

  return batchProcessEmailJobs(resendJobs);
}
