// Task Team — API Bridge / Connectors — 2026-03-29
async function connectorRoutes(app) {
    // List connectors
    app.get('/connectors', async (req) => {
        const { rows } = await app.db.query('SELECT id, type, enabled, last_sync_at, created_at FROM connectors ORDER BY created_at DESC');
        return { data: rows };
    });

    // Get connector
    app.get('/connectors/:id', async (req) => {
        const { rows } = await app.db.query('SELECT * FROM connectors WHERE id = $1', [req.params.id]);
        if (!rows.length) throw { statusCode: 404, message: 'Connector not found' };
        return { data: rows[0] };
    });

    // Create connector
    app.post('/connectors', async (req) => {
        const { type, config, user_id } = req.body;
        const { rows } = await app.db.query(
            'INSERT INTO connectors (user_id, type, config) VALUES ($1, $2, $3) RETURNING *',
            [user_id, type, JSON.stringify(config || {})]
        );
        return { data: rows[0] };
    });

    // Sync connector
    app.post('/connectors/:id/sync', async (req) => {
        const { rows } = await app.db.query('SELECT * FROM connectors WHERE id = $1', [req.params.id]);
        if (!rows.length) throw { statusCode: 404, message: 'Connector not found' };
        // TODO: dispatch sync job to n8n or Redis queue
        await app.db.query('UPDATE connectors SET last_sync_at = NOW() WHERE id = $1', [req.params.id]);
        return { status: 'sync_started', connector: rows[0].type };
    });

    // Generic webhook
    app.post('/connectors/webhook/:type', async (req) => {
        const { type } = req.params;
        // Log webhook
        app.log.info({ type, body: req.body }, 'Webhook received');
        // TODO: process based on type (odoo, moodle, pohoda, generic)
        return { status: 'received', type };
    });

    // Toggle connector
    app.put('/connectors/:id/toggle', async (req) => {
        const { rows } = await app.db.query(
            'UPDATE connectors SET enabled = NOT enabled, updated_at = NOW() WHERE id = $1 RETURNING id, type, enabled',
            [req.params.id]
        );
        if (!rows.length) throw { statusCode: 404, message: 'Connector not found' };
        return { data: rows[0] };
    });
}

module.exports = connectorRoutes;
