"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = userbotRoutes;
const logger_js_1 = require("../utils/logger.js");
const log = (0, logger_js_1.createModuleLogger)('userbot-routes');
// Pending login sessions waiting for verification code
const pendingLogins = new Map();
async function userbotRoutes(app, opts) {
    const { userbotManager } = opts;
    // POST /userbot/login/start — Start login (sends SMS code)
    app.post('/userbot/login/start', async (request, reply) => {
        const body = request.body;
        if (!body?.characterId || !body?.phoneNumber) {
            return reply.status(400).send({ success: false, error: 'characterId and phoneNumber are required' });
        }
        const { characterId, phoneNumber } = body;
        // Check if already pending
        if (pendingLogins.has(characterId)) {
            return reply.status(400).send({ success: false, error: 'Login already in progress for this character' });
        }
        try {
            let resolveCode;
            const codePromise = new Promise((resolve) => {
                resolveCode = resolve;
            });
            let resolvePassword;
            const passwordPromise = new Promise((resolve) => {
                resolvePassword = resolve;
            });
            const loginPromise = userbotManager.login(characterId, phoneNumber, () => codePromise, () => passwordPromise);
            pendingLogins.set(characterId, {
                characterId,
                phoneNumber,
                resolveCode,
                resolvePassword,
                loginPromise,
            });
            // Auto-cleanup after 5 minutes
            setTimeout(() => {
                pendingLogins.delete(characterId);
            }, 5 * 60 * 1000);
            return reply.status(200).send({
                success: true,
                data: { message: 'Doğrulama kodu gönderildi. /userbot/login/verify ile kodu gönderin.', characterId },
            });
        }
        catch (err) {
            return reply.status(500).send({ success: false, error: err.message });
        }
    });
    // POST /userbot/login/verify — Submit verification code
    app.post('/userbot/login/verify', async (request, reply) => {
        const body = request.body;
        if (!body?.characterId) {
            return reply.status(400).send({ success: false, error: 'characterId is required' });
        }
        const pending = pendingLogins.get(body.characterId);
        if (!pending) {
            return reply.status(404).send({ success: false, error: 'No pending login for this character. Start login first.' });
        }
        try {
            if (body.password && pending.resolvePassword) {
                pending.resolvePassword(body.password);
            }
            else if (body.code) {
                pending.resolveCode(body.code);
            }
            else {
                return reply.status(400).send({ success: false, error: 'code or password is required' });
            }
            // Wait for login to complete (with timeout)
            const result = await Promise.race([
                pending.loginPromise,
                new Promise((_, reject) => setTimeout(() => reject(new Error('Login timeout')), 30000)),
            ]);
            pendingLogins.delete(body.characterId);
            return reply.status(200).send({
                success: true,
                data: { message: 'Giriş başarılı!', characterId: body.characterId },
            });
        }
        catch (err) {
            pendingLogins.delete(body.characterId);
            // If 2FA is needed, the error message will indicate it
            if (err.message?.includes('password') || err.message?.includes('2FA')) {
                return reply.status(200).send({
                    success: true,
                    data: { needsPassword: true, message: '2FA şifresi gerekli. password alanıyla tekrar gönderin.', characterId: body.characterId },
                });
            }
            return reply.status(400).send({ success: false, error: err.message });
        }
    });
    // POST /userbot/logout — Disconnect userbot
    app.post('/userbot/logout', async (request, reply) => {
        const body = request.body;
        if (!body?.characterId) {
            return reply.status(400).send({ success: false, error: 'characterId is required' });
        }
        try {
            await userbotManager.disconnect(body.characterId);
            return reply.status(200).send({ success: true, data: { message: 'Çıkış yapıldı.' } });
        }
        catch (err) {
            return reply.status(500).send({ success: false, error: err.message });
        }
    });
    // GET /userbot/sessions — List active sessions
    app.get('/userbot/sessions', async (_request, reply) => {
        try {
            const sessions = await userbotManager.getSessions();
            // Don't expose session strings
            const safe = sessions.map(s => ({
                characterId: s.characterId,
                phoneNumber: s.phoneNumber.replace(/(\+\d{2})\d+(\d{2})/, '$1***$2'),
                active: s.active,
                createdAt: s.createdAt,
            }));
            return reply.status(200).send({ success: true, data: safe });
        }
        catch (err) {
            return reply.status(500).send({ success: false, error: err.message });
        }
    });
    // GET /userbot/status/:characterId — Get userbot status
    app.get('/userbot/status/:characterId', async (request, reply) => {
        const { characterId } = request.params;
        const client = userbotManager.getClient(characterId);
        return reply.status(200).send({
            success: true,
            data: {
                characterId,
                connected: client?.isConnected() ?? false,
            },
        });
    });
    // PUT /userbot/profile/:characterId — Update Telegram profile (name, bio)
    app.put('/userbot/profile/:characterId', async (request, reply) => {
        const { characterId } = request.params;
        const body = request.body;
        if (!body) {
            return reply.status(400).send({ success: false, error: 'Request body is required' });
        }
        const client = userbotManager.getClient(characterId);
        if (!client || !client.isConnected()) {
            return reply.status(400).send({ success: false, error: 'Userbot not connected for this character' });
        }
        try {
            await client.updateProfile(body);
            return reply.status(200).send({ success: true, data: { message: 'Profil güncellendi', ...body } });
        }
        catch (err) {
            return reply.status(500).send({ success: false, error: err.message });
        }
    });
    // POST /userbot/profile/:characterId/photo — Update Telegram profile photo
    app.post('/userbot/profile/:characterId/photo', async (request, reply) => {
        const { characterId } = request.params;
        const body = request.body;
        if (!body?.imageUrl) {
            return reply.status(400).send({ success: false, error: 'imageUrl is required' });
        }
        const client = userbotManager.getClient(characterId);
        if (!client || !client.isConnected()) {
            return reply.status(400).send({ success: false, error: 'Userbot not connected for this character' });
        }
        try {
            const { fetch } = await import('undici');
            const response = await fetch(body.imageUrl);
            if (!response.ok)
                throw new Error('Failed to download image');
            const buffer = Buffer.from(await response.arrayBuffer());
            await client.updateProfilePhoto(buffer);
            return reply.status(200).send({ success: true, data: { message: 'Profil fotoğrafı güncellendi' } });
        }
        catch (err) {
            return reply.status(500).send({ success: false, error: err.message });
        }
    });
    // POST /userbot/chat/:characterId/:chatId/photo — Update channel/group profile photo
    app.post('/userbot/chat/:characterId/:chatId/photo', async (request, reply) => {
        const { characterId, chatId } = request.params;
        const body = request.body;
        if (!body?.imageUrl) {
            return reply.status(400).send({ success: false, error: 'imageUrl is required' });
        }
        const client = userbotManager.getClient(characterId);
        if (!client || !client.isConnected()) {
            return reply.status(400).send({ success: false, error: 'Userbot not connected for this character' });
        }
        try {
            const { fetch } = await import('undici');
            let imageBuffer;
            if (body.imageUrl.startsWith('/static/')) {
                // Local file
                const { readFile } = await import('fs/promises');
                const { resolve } = await import('path');
                const { config } = await import('../utils/config.js');
                const filePath = resolve(config.dataDir, body.imageUrl.replace('/static/', ''));
                imageBuffer = await readFile(filePath);
            }
            else {
                const response = await fetch(body.imageUrl);
                if (!response.ok)
                    throw new Error('Failed to download image');
                imageBuffer = Buffer.from(await response.arrayBuffer());
            }
            await client.updateChatPhoto(Number(chatId), imageBuffer);
            return reply.status(200).send({ success: true, data: { message: 'Kanal fotoğrafı güncellendi' } });
        }
        catch (err) {
            return reply.status(500).send({ success: false, error: err.message });
        }
    });
}
//# sourceMappingURL=userbot.js.map