import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import Fastify from 'fastify';
import cookie from '@fastify/cookie';
import Database from 'better-sqlite3';
import { leadRoutes } from '../lead-routes.js';
import { registerAuthMiddleware } from '../../auth/auth-middleware.js';
import { authRoutes } from '../../auth/auth-routes.js';
import { hashPassword } from '../../auth/password.js';
import { runMigrations } from '../../db/migrations.js';
const SECRET = 'test-secret-that-is-at-least-32-chars-long!!';
async function buildApp(db) {
    const app = Fastify();
    await app.register(cookie);
    registerAuthMiddleware(app, SECRET);
    await app.register(authRoutes, { db, jwtSecret: SECRET });
    await app.register(leadRoutes, { db });
    await app.ready();
    return app;
}
async function getAuthCookie(app) {
    const res = await app.inject({
        method: 'POST',
        url: '/api/auth/login',
        payload: { username: 'admin', password: 'admin123' },
    });
    const cookies = res.cookies;
    const accessToken = cookies.find(c => c.name === 'access_token');
    return `access_token=${accessToken.value}`;
}
describe('lead routes', () => {
    let db;
    let app;
    let authCookie;
    beforeEach(async () => {
        db = new Database(':memory:');
        runMigrations(db);
        const hash = await hashPassword('admin123');
        db.prepare("INSERT INTO users (id, username, password_hash, role, created_at) VALUES (?, ?, ?, ?, ?)").run('admin-id', 'admin', hash, 'admin', new Date().toISOString());
        app = await buildApp(db);
        authCookie = await getAuthCookie(app);
    });
    afterEach(async () => {
        await app?.close();
        db?.close();
    });
    it('POST /api/email/leads — creates a lead', async () => {
        const res = await app.inject({
            method: 'POST',
            url: '/api/email/leads',
            headers: { cookie: authCookie },
            payload: { email: 'a@b.com', name: 'Alice' },
        });
        expect(res.statusCode).toBe(200);
        const body = JSON.parse(res.payload);
        expect(body.lead.email).toBe('a@b.com');
        expect(body.lead.id).toBeDefined();
    });
    it('GET /api/email/leads — lists leads', async () => {
        await app.inject({
            method: 'POST',
            url: '/api/email/leads',
            headers: { cookie: authCookie },
            payload: { email: 'x@y.com' },
        });
        const res = await app.inject({
            method: 'GET',
            url: '/api/email/leads',
            headers: { cookie: authCookie },
        });
        expect(res.statusCode).toBe(200);
        const body = JSON.parse(res.payload);
        expect(body.data.length).toBe(1);
        expect(body.total).toBe(1);
    });
    it('POST /api/email/leads/batch — imports leads', async () => {
        const res = await app.inject({
            method: 'POST',
            url: '/api/email/leads/batch',
            headers: { cookie: authCookie },
            payload: {
                leads: [
                    { email: 'a@b.com', name: 'Alice' },
                    { email: 'c@d.com', name: 'Bob' },
                ],
                source_detail: 'test-import',
                source: 'csv_import',
            },
        });
        expect(res.statusCode).toBe(200);
        const body = JSON.parse(res.payload);
        expect(body.imported).toBe(2);
    });
    it('PATCH /api/email/leads/:id — updates a lead', async () => {
        const createRes = await app.inject({
            method: 'POST',
            url: '/api/email/leads',
            headers: { cookie: authCookie },
            payload: { email: 'a@b.com', name: 'Alice' },
        });
        const id = JSON.parse(createRes.payload).lead.id;
        const res = await app.inject({
            method: 'PATCH',
            url: `/api/email/leads/${id}`,
            headers: { cookie: authCookie },
            payload: { name: 'Alice Updated' },
        });
        expect(res.statusCode).toBe(200);
        expect(JSON.parse(res.payload).lead.name).toBe('Alice Updated');
    });
    it('DELETE /api/email/leads/:id — deletes a lead', async () => {
        const createRes = await app.inject({
            method: 'POST',
            url: '/api/email/leads',
            headers: { cookie: authCookie },
            payload: { email: 'a@b.com' },
        });
        const id = JSON.parse(createRes.payload).lead.id;
        const res = await app.inject({
            method: 'DELETE',
            url: `/api/email/leads/${id}`,
            headers: { cookie: authCookie },
        });
        expect(res.statusCode).toBe(200);
        expect(JSON.parse(res.payload).ok).toBe(true);
    });
    it('POST /api/email/leads/:id/tags — adds tags', async () => {
        const createRes = await app.inject({
            method: 'POST',
            url: '/api/email/leads',
            headers: { cookie: authCookie },
            payload: { email: 'a@b.com' },
        });
        const id = JSON.parse(createRes.payload).lead.id;
        const res = await app.inject({
            method: 'POST',
            url: `/api/email/leads/${id}/tags`,
            headers: { cookie: authCookie },
            payload: { tags: ['vip', 'beta'] },
        });
        expect(res.statusCode).toBe(200);
        const body = JSON.parse(res.payload);
        expect(body.tags).toContain('vip');
        expect(body.tags).toContain('beta');
    });
    it('POST /api/email/leads/:id/lists — adds to lists', async () => {
        const createRes = await app.inject({
            method: 'POST',
            url: '/api/email/leads',
            headers: { cookie: authCookie },
            payload: { email: 'a@b.com' },
        });
        const id = JSON.parse(createRes.payload).lead.id;
        const res = await app.inject({
            method: 'POST',
            url: `/api/email/leads/${id}/lists`,
            headers: { cookie: authCookie },
            payload: { lists: ['newsletter', 'onboarding'] },
        });
        expect(res.statusCode).toBe(200);
        const body = JSON.parse(res.payload);
        expect(body.lists).toContain('newsletter');
    });
    it('GET /api/email/leads/lists — returns lists with counts', async () => {
        const res = await app.inject({
            method: 'GET',
            url: '/api/email/leads/lists',
            headers: { cookie: authCookie },
        });
        expect(res.statusCode).toBe(200);
        expect(JSON.parse(res.payload).lists).toBeDefined();
    });
    it('rejects unauthenticated requests', async () => {
        const res = await app.inject({
            method: 'GET',
            url: '/api/email/leads',
        });
        expect(res.statusCode).toBe(401);
    });
});
//# sourceMappingURL=lead-routes.test.js.map