import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import Database from 'better-sqlite3';
import { runMigrations } from '../../db/migrations.js';
import { processSnsNotification } from '../sns-webhook.js';
describe('SNS webhook processing', () => {
    let db;
    beforeEach(() => {
        db = new Database(':memory:');
        runMigrations(db);
        db.prepare("INSERT INTO leads (id, email) VALUES ('l1', 'user@test.com')").run();
        db.prepare("INSERT INTO email_campaigns (id, name, subject, body_html, from_email, status, total_recipients) VALUES ('c1', 'Test', 'Hi', '<p>Hi</p>', 'a@b.com', 'sending', 1)").run();
        db.prepare("INSERT INTO email_queue (id, campaign_id, lead_id, to_email, status, ses_message_id) VALUES ('q1', 'c1', 'l1', 'user@test.com', 'sent', 'ses-123')").run();
    });
    afterEach(() => { db.close(); });
    it('should process bounce notification', () => {
        processSnsNotification(db, { notificationType: 'Bounce', mail: { messageId: 'ses-123' }, bounce: { bounceType: 'Permanent' } });
        const row = db.prepare("SELECT status FROM email_queue WHERE id = 'q1'").get();
        expect(row.status).toBe('bounced');
        const lead = db.prepare("SELECT status FROM leads WHERE id = 'l1'").get();
        expect(lead.status).toBe('bounced');
        const campaign = db.prepare("SELECT bounce_count FROM email_campaigns WHERE id = 'c1'").get();
        expect(campaign.bounce_count).toBe(1);
    });
    it('should process complaint notification', () => {
        processSnsNotification(db, { notificationType: 'Complaint', mail: { messageId: 'ses-123' } });
        const row = db.prepare("SELECT status FROM email_queue WHERE id = 'q1'").get();
        expect(row.status).toBe('complained');
    });
    it('should be idempotent — skip if already bounced', () => {
        db.prepare("UPDATE email_queue SET status = 'bounced' WHERE id = 'q1'").run();
        db.prepare("UPDATE email_campaigns SET bounce_count = 1 WHERE id = 'c1'").run();
        processSnsNotification(db, { notificationType: 'Bounce', mail: { messageId: 'ses-123' }, bounce: { bounceType: 'Permanent' } });
        const campaign = db.prepare("SELECT bounce_count FROM email_campaigns WHERE id = 'c1'").get();
        expect(campaign.bounce_count).toBe(1); // not incremented again
    });
    it('should ignore unknown message IDs', () => {
        expect(() => processSnsNotification(db, { notificationType: 'Bounce', mail: { messageId: 'unknown-id' }, bounce: { bounceType: 'Permanent' } })).not.toThrow();
    });
});
//# sourceMappingURL=sns-webhook.test.js.map