import { describe, it, expect, beforeAll } from 'vitest';
import { initializeBrevo, sendEmailCampaign, validateEmailList } from './_core/brevo.ts';
import { getTemplate, renderTemplate, validateTemplateVariables } from './_core/emailTemplates.ts';

describe('Email Campaign End-to-End', () => {
  beforeAll(() => {
    // Initialize Brevo
    const initialized = initializeBrevo({
      host: process.env.BREVO_SMTP_HOST || 'smtp-relay.brevo.com',
      port: parseInt(process.env.BREVO_SMTP_PORT || '587'),
      user: process.env.BREVO_SMTP_USER || '',
      pass: process.env.BREVO_SMTP_PASS || '',
    });
    expect(initialized).toBe(true);
  });

  it('should create a welcome campaign with valid template', () => {
    const template = getTemplate('welcome_campaign');
    expect(template).toBeDefined();
    expect(template?.category).toBe('campaign');

    // Validate template variables
    const validation = validateTemplateVariables(template!, {
      firstName: 'John',
      loginUrl: 'https://playcoinkrazy.com/login',
    });
    expect(validation.valid).toBe(true);
  });

  it('should render campaign template with variables', () => {
    const template = getTemplate('welcome_campaign');
    expect(template).toBeDefined();

    const rendered = renderTemplate(template!, {
      firstName: 'Alice',
      loginUrl: 'https://playcoinkrazy.com/login?ref=campaign',
    });

    expect(rendered.subject).toContain('Welcome');
    expect(rendered.htmlContent).toContain('Alice');
    expect(rendered.htmlContent).toContain('https://playcoinkrazy.com/login?ref=campaign');
  });

  it('should validate recipient email list', () => {
    const recipients = [
      'valid@example.com',
      'another.valid@test.co.uk',
      'invalid-email',
      'also@valid.com',
    ];

    const { valid, invalid } = validateEmailList(recipients);

    expect(valid).toHaveLength(3);
    expect(invalid).toHaveLength(1);
    expect(invalid).toContain('invalid-email');
  });

  it('should prepare campaign payload', () => {
    const template = getTemplate('promotional_offer');
    expect(template).toBeDefined();

    const rendered = renderTemplate(template!, {
      firstName: 'Bob',
      offerTitle: '50% Bonus',
      offerDescription: 'Get 50% bonus on your next deposit!',
      offerAmount: '$50 Bonus',
      promoCode: 'SAVE50',
      claimUrl: 'https://playcoinkrazy.com/claim?code=SAVE50',
      expiryDate: '2026-05-15',
    });

    const recipients = ['bob@example.com', 'test@example.com'];
    const { valid: validEmails } = validateEmailList(recipients);

    const payload = {
      campaignId: 'promo-001',
      subject: rendered.subject,
      htmlContent: rendered.htmlContent,
      recipients: validEmails,
      fromEmail: 'noreply@playcoinkrazy.com',
      fromName: 'CoinKrazy',
      trackingEnabled: true,
    };

    expect(payload.campaignId).toBe('promo-001');
    expect(payload.recipients).toHaveLength(2);
    expect(payload.subject).toContain('Special Offer');
    expect(payload.htmlContent).toContain('SAVE50');
  });

  it('should handle campaign with multiple segments', () => {
    const segments = {
      all: ['user1@example.com', 'user2@example.com', 'user3@example.com'],
      vip: ['vip1@example.com', 'vip2@example.com'],
      new: ['newuser@example.com'],
    };

    Object.entries(segments).forEach(([segment, emails]) => {
      const { valid } = validateEmailList(emails);
      expect(valid.length).toBeGreaterThan(0);
      expect(valid).toEqual(emails);
    });
  });

  it('should validate all template types', () => {
    const templates = [
      'welcome_campaign',
      'promotional_offer',
      'password_reset',
      'email_verification',
      're_engagement',
    ];

    templates.forEach((templateId) => {
      const template = getTemplate(templateId);
      expect(template).toBeDefined();
      expect(template?.variables.length).toBeGreaterThan(0);
    });
  });

  it('should prepare re-engagement campaign', () => {
    const template = getTemplate('re_engagement');
    expect(template).toBeDefined();

    const rendered = renderTemplate(template!, {
      firstName: 'Charlie',
      bonusAmount: '$25 Free Credits',
      loginUrl: 'https://playcoinkrazy.com/login?comeback=true',
      expiryDate: '2026-05-20',
    });

    expect(rendered.subject).toContain('Miss You');
    expect(rendered.htmlContent).toContain('Charlie');
    expect(rendered.htmlContent).toContain('$25 Free Credits');
  });

  it('should handle campaign with custom variables', () => {
    const template = getTemplate('promotional_offer');
    expect(template).toBeDefined();

    const customVars = {
      firstName: 'Diana',
      offerTitle: 'VIP Exclusive Deal',
      offerDescription: 'As a VIP member, enjoy this exclusive offer',
      offerAmount: '$100 Bonus',
      promoCode: 'VIP100',
      claimUrl: 'https://playcoinkrazy.com/vip/claim',
      expiryDate: '2026-06-01',
    };

    const validation = validateTemplateVariables(template!, customVars);
    expect(validation.valid).toBe(true);

    const rendered = renderTemplate(template!, customVars);
    expect(rendered.htmlContent).toContain('Diana');
    expect(rendered.htmlContent).toContain('VIP100');
  });
});
