import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import Database from 'better-sqlite3';
import { runMigrations } from '../migrations.js';
describe('email schema', () => {
    let db;
    beforeEach(() => {
        db = new Database(':memory:');
        runMigrations(db);
    });
    afterEach(() => { db.close(); });
    it('should create leads table', () => {
        const row = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='leads'").get();
        expect(row).toBeTruthy();
    });
    it('should create lead_tags table', () => {
        const row = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='lead_tags'").get();
        expect(row).toBeTruthy();
    });
    it('should create lead_lists table', () => {
        const row = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='lead_lists'").get();
        expect(row).toBeTruthy();
    });
    it('should create email_campaigns table', () => {
        const row = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='email_campaigns'").get();
        expect(row).toBeTruthy();
    });
    it('should create email_queue table', () => {
        const row = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='email_queue'").get();
        expect(row).toBeTruthy();
    });
    it('should enforce unique email on leads', () => {
        db.prepare("INSERT INTO leads (id, email) VALUES ('a', 'test@example.com')").run();
        expect(() => {
            db.prepare("INSERT INTO leads (id, email) VALUES ('b', 'test@example.com')").run();
        }).toThrow();
    });
    it('should cascade delete lead_tags when lead is deleted', () => {
        db.prepare("INSERT INTO leads (id, email) VALUES ('a', 'test@example.com')").run();
        db.prepare("INSERT INTO lead_tags (lead_id, tag) VALUES ('a', 'saas')").run();
        db.prepare("DELETE FROM leads WHERE id = 'a'").run();
        const tags = db.prepare("SELECT * FROM lead_tags WHERE lead_id = 'a'").all();
        expect(tags).toHaveLength(0);
    });
    it('should set null on email_queue.lead_id when lead is deleted', () => {
        db.prepare("INSERT INTO leads (id, email) VALUES ('a', 'test@example.com')").run();
        db.prepare("INSERT INTO email_campaigns (id, name, subject, body_html, from_email) VALUES ('c1', 'Test', 'Hi', '<p>Hi</p>', 'a@b.com')").run();
        db.prepare("INSERT INTO email_queue (id, campaign_id, lead_id, to_email) VALUES ('q1', 'c1', 'a', 'test@example.com')").run();
        db.prepare("DELETE FROM leads WHERE id = 'a'").run();
        const row = db.prepare("SELECT lead_id FROM email_queue WHERE id = 'q1'").get();
        expect(row.lead_id).toBeNull();
    });
});
//# sourceMappingURL=email-schema.test.js.map