"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const vitest_1 = require("vitest");
const fastify_1 = __importDefault(require("fastify"));
const telegram_management_js_1 = __importDefault(require("./telegram-management.js"));
// Mock file-ops to avoid real filesystem access
vitest_1.vi.mock('../modules/data-store/file-ops.js', () => ({
    readJSON: vitest_1.vi.fn().mockResolvedValue([]),
    atomicWriteJSON: vitest_1.vi.fn().mockResolvedValue(undefined),
}));
function createMockUserbotClient(overrides = {}) {
    return {
        createGroup: vitest_1.vi.fn().mockResolvedValue({ chatId: 12345, inviteLink: 'https://t.me/+abc123' }),
        createChannel: vitest_1.vi.fn().mockResolvedValue({ chatId: 67890, inviteLink: 'https://t.me/+xyz789' }),
        sendMessage: vitest_1.vi.fn().mockResolvedValue(undefined),
        ...overrides,
    };
}
function createMockUserbotManager(client = null) {
    return {
        getClient: vitest_1.vi.fn().mockReturnValue(client),
    };
}
function createMockDataStore() {
    return {};
}
async function buildApp(opts = {}) {
    const app = (0, fastify_1.default)();
    const client = opts.client ?? null;
    const userbotManager = createMockUserbotManager(client);
    await app.register(telegram_management_js_1.default, {
        userbotManager,
        dataStore: createMockDataStore(),
    });
    return { app, userbotManager };
}
(0, vitest_1.describe)('telegram-management routes', () => {
    (0, vitest_1.describe)('POST /characters/:id/telegram/groups', () => {
        (0, vitest_1.it)('returns 400 when no active userbot session', async () => {
            const { app } = await buildApp();
            const res = await app.inject({
                method: 'POST',
                url: '/characters/char-1/telegram/groups',
                payload: { title: 'Test Group' },
            });
            (0, vitest_1.expect)(res.statusCode).toBe(400);
            const body = res.json();
            (0, vitest_1.expect)(body.success).toBe(false);
            (0, vitest_1.expect)(body.error).toBe('Bu karakter için aktif userbot oturumu yok');
        });
        (0, vitest_1.it)('returns 400 when title is missing', async () => {
            const client = createMockUserbotClient();
            const { app } = await buildApp({ client });
            const res = await app.inject({
                method: 'POST',
                url: '/characters/char-1/telegram/groups',
                payload: { description: 'No title' },
            });
            (0, vitest_1.expect)(res.statusCode).toBe(400);
            (0, vitest_1.expect)(res.json().error).toContain('title');
        });
        (0, vitest_1.it)('creates group with real GramJS chatId', async () => {
            const client = createMockUserbotClient();
            const { app } = await buildApp({ client });
            const res = await app.inject({
                method: 'POST',
                url: '/characters/char-1/telegram/groups',
                payload: { title: 'My Group', description: 'A test group', groupType: 'normal' },
            });
            (0, vitest_1.expect)(res.statusCode).toBe(201);
            const body = res.json();
            (0, vitest_1.expect)(body.success).toBe(true);
            (0, vitest_1.expect)(body.data.telegramChatId).toBe(12345);
            (0, vitest_1.expect)(body.data.inviteLink).toBe('https://t.me/+abc123');
            (0, vitest_1.expect)(body.data.type).toBe('group');
            (0, vitest_1.expect)(body.data.title).toBe('My Group');
            (0, vitest_1.expect)(client.createGroup).toHaveBeenCalledWith('My Group', 'A test group', false);
        });
        (0, vitest_1.it)('creates supergroup with real GramJS chatId', async () => {
            const client = createMockUserbotClient({
                createGroup: vitest_1.vi.fn().mockResolvedValue({ chatId: 99999, inviteLink: 'https://t.me/+super' }),
            });
            const { app } = await buildApp({ client });
            const res = await app.inject({
                method: 'POST',
                url: '/characters/char-1/telegram/groups',
                payload: { title: 'Super Group', groupType: 'supergroup' },
            });
            (0, vitest_1.expect)(res.statusCode).toBe(201);
            const body = res.json();
            (0, vitest_1.expect)(body.data.telegramChatId).toBe(99999);
            (0, vitest_1.expect)(body.data.type).toBe('supergroup');
            (0, vitest_1.expect)(client.createGroup).toHaveBeenCalledWith('Super Group', undefined, true);
        });
        (0, vitest_1.it)('returns 502 with retryable flag on GramJS error', async () => {
            const client = createMockUserbotClient({
                createGroup: vitest_1.vi.fn().mockRejectedValue(new Error('FLOOD_WAIT_30')),
            });
            const { app } = await buildApp({ client });
            const res = await app.inject({
                method: 'POST',
                url: '/characters/char-1/telegram/groups',
                payload: { title: 'Fail Group' },
            });
            (0, vitest_1.expect)(res.statusCode).toBe(502);
            const body = res.json();
            (0, vitest_1.expect)(body.success).toBe(false);
            (0, vitest_1.expect)(body.error).toContain('Telegram işlemi başarısız');
            (0, vitest_1.expect)(body.error).toContain('FLOOD_WAIT_30');
            (0, vitest_1.expect)(body.retryable).toBe(true);
        });
    });
    (0, vitest_1.describe)('POST /characters/:id/telegram/channels', () => {
        (0, vitest_1.it)('returns 400 when no active userbot session', async () => {
            const { app } = await buildApp();
            const res = await app.inject({
                method: 'POST',
                url: '/characters/char-1/telegram/channels',
                payload: { title: 'Test Channel' },
            });
            (0, vitest_1.expect)(res.statusCode).toBe(400);
            (0, vitest_1.expect)(res.json().error).toBe('Bu karakter için aktif userbot oturumu yok');
        });
        (0, vitest_1.it)('creates channel with real GramJS chatId', async () => {
            const client = createMockUserbotClient();
            const { app } = await buildApp({ client });
            const res = await app.inject({
                method: 'POST',
                url: '/characters/char-1/telegram/channels',
                payload: { title: 'My Channel', description: 'A test channel', channelType: 'public' },
            });
            (0, vitest_1.expect)(res.statusCode).toBe(201);
            const body = res.json();
            (0, vitest_1.expect)(body.success).toBe(true);
            (0, vitest_1.expect)(body.data.telegramChatId).toBe(67890);
            (0, vitest_1.expect)(body.data.inviteLink).toBe('https://t.me/+xyz789');
            (0, vitest_1.expect)(body.data.type).toBe('channel');
            (0, vitest_1.expect)(body.data.isVip).toBe(false);
            (0, vitest_1.expect)(client.createChannel).toHaveBeenCalledWith('My Channel', 'A test channel');
        });
        (0, vitest_1.it)('creates VIP channel with starPrice', async () => {
            const client = createMockUserbotClient();
            const { app } = await buildApp({ client });
            const res = await app.inject({
                method: 'POST',
                url: '/characters/char-1/telegram/channels',
                payload: { title: 'VIP Channel', channelType: 'vip', starPrice: 100 },
            });
            (0, vitest_1.expect)(res.statusCode).toBe(201);
            const body = res.json();
            (0, vitest_1.expect)(body.data.isVip).toBe(true);
            (0, vitest_1.expect)(body.data.starPrice).toBe(100);
            (0, vitest_1.expect)(body.data.telegramChatId).toBe(67890);
        });
        (0, vitest_1.it)('returns 502 with retryable flag on GramJS error', async () => {
            const client = createMockUserbotClient({
                createChannel: vitest_1.vi.fn().mockRejectedValue(new Error('CHANNELS_TOO_MUCH')),
            });
            const { app } = await buildApp({ client });
            const res = await app.inject({
                method: 'POST',
                url: '/characters/char-1/telegram/channels',
                payload: { title: 'Fail Channel' },
            });
            (0, vitest_1.expect)(res.statusCode).toBe(502);
            const body = res.json();
            (0, vitest_1.expect)(body.retryable).toBe(true);
            (0, vitest_1.expect)(body.error).toContain('CHANNELS_TOO_MUCH');
        });
    });
    (0, vitest_1.describe)('POST /characters/:id/telegram/entities/:entityId/publish', () => {
        (0, vitest_1.it)('returns 400 when no active userbot session', async () => {
            // Need to set up entities so entity is found first
            const { readJSON } = await import('../modules/data-store/file-ops.js');
            readJSON.mockResolvedValue([
                { id: 'ent-1', characterId: 'char-1', telegramChatId: 12345, type: 'channel', title: 'Ch' },
            ]);
            const { app } = await buildApp();
            const res = await app.inject({
                method: 'POST',
                url: '/characters/char-1/telegram/entities/ent-1/publish',
                payload: { text: 'Hello world' },
            });
            (0, vitest_1.expect)(res.statusCode).toBe(400);
            (0, vitest_1.expect)(res.json().error).toBe('Bu karakter için aktif userbot oturumu yok');
        });
        (0, vitest_1.it)('publishes content via real GramJS sendMessage', async () => {
            const { readJSON } = await import('../modules/data-store/file-ops.js');
            readJSON.mockResolvedValue([
                { id: 'ent-1', characterId: 'char-1', telegramChatId: 12345, type: 'channel', title: 'Ch' },
            ]);
            const client = createMockUserbotClient();
            const { app } = await buildApp({ client });
            const res = await app.inject({
                method: 'POST',
                url: '/characters/char-1/telegram/entities/ent-1/publish',
                payload: { text: 'Hello world', imageUrl: 'https://example.com/img.jpg' },
            });
            (0, vitest_1.expect)(res.statusCode).toBe(200);
            const body = res.json();
            (0, vitest_1.expect)(body.success).toBe(true);
            (0, vitest_1.expect)(body.data.published).toBe(true);
            (0, vitest_1.expect)(client.sendMessage).toHaveBeenCalledWith(12345, 'Hello world', 'https://example.com/img.jpg');
        });
        (0, vitest_1.it)('returns 502 with retryable flag on GramJS sendMessage error', async () => {
            const { readJSON } = await import('../modules/data-store/file-ops.js');
            readJSON.mockResolvedValue([
                { id: 'ent-1', characterId: 'char-1', telegramChatId: 12345, type: 'channel', title: 'Ch' },
            ]);
            const client = createMockUserbotClient({
                sendMessage: vitest_1.vi.fn().mockRejectedValue(new Error('PEER_ID_INVALID')),
            });
            const { app } = await buildApp({ client });
            const res = await app.inject({
                method: 'POST',
                url: '/characters/char-1/telegram/entities/ent-1/publish',
                payload: { text: 'Hello' },
            });
            (0, vitest_1.expect)(res.statusCode).toBe(502);
            const body = res.json();
            (0, vitest_1.expect)(body.retryable).toBe(true);
            (0, vitest_1.expect)(body.error).toContain('PEER_ID_INVALID');
        });
        (0, vitest_1.it)('returns 404 when entity not found', async () => {
            const { readJSON } = await import('../modules/data-store/file-ops.js');
            readJSON.mockResolvedValue([]);
            const client = createMockUserbotClient();
            const { app } = await buildApp({ client });
            const res = await app.inject({
                method: 'POST',
                url: '/characters/char-1/telegram/entities/nonexistent/publish',
                payload: { text: 'Hello' },
            });
            (0, vitest_1.expect)(res.statusCode).toBe(404);
        });
    });
});
//# sourceMappingURL=telegram-management.test.js.map