import { parseEnvFile, writeEnvFile } from './settings-routes.js';
export const PROVIDER_CATALOG = [
    { key: 'active_campaign', name: 'ActiveCampaign', category: 'email', description: 'Automação de marketing e CRM', fields: [
            { key: 'api_url', label: 'API URL', type: 'url', required: true, placeholder: 'https://myaccount.api-us1.com' },
            { key: 'api_key', label: 'API Key', type: 'password', required: true },
        ] },
    { key: 'asaas', name: 'Asaas', category: 'sales', description: 'Cobranças, assinaturas e Pix para SaaS brasileiro', fields: [
            { key: 'api_key', label: 'API Key', type: 'password', required: true, placeholder: '$aact_...' },
            { key: 'environment', label: 'Environment', type: 'text', placeholder: 'production ou sandbox' },
            { key: 'webhook_token', label: 'Webhook Token', type: 'password' },
        ] },
    { key: 'bitbucket', name: 'Bitbucket', category: 'dev', description: 'Repositórios Git e pipelines (Atlassian)', fields: [
            { key: 'username', label: 'Username', type: 'text', required: true },
            { key: 'app_password', label: 'App Password', type: 'password', required: true },
            { key: 'workspace', label: 'Workspace', type: 'text', required: true },
        ] },
    { key: 'brevo', name: 'Brevo', category: 'email', description: 'Email marketing e automação (ex-Sendinblue)', fields: [
            { key: 'api_key', label: 'API Key', type: 'password', required: true, placeholder: 'xkeysib-...' },
        ] },
    { key: 'cloudflare', name: 'Cloudflare', category: 'cloud', description: 'DNS, CDN, Workers e segurança', fields: [
            { key: 'api_token', label: 'API Token', type: 'password', required: true },
            { key: 'account_id', label: 'Account ID', type: 'text', required: true },
            { key: 'zone_id', label: 'Default Zone ID', type: 'text' },
        ] },
    { key: 'confluence', name: 'Confluence', category: 'pm', description: 'Documentação e wikis (Atlassian)', fields: [
            { key: 'base_url', label: 'Base URL', type: 'url', required: true, placeholder: 'https://mycompany.atlassian.net/wiki' },
            { key: 'email', label: 'Email', type: 'text', required: true },
            { key: 'api_token', label: 'API Token', type: 'password', required: true },
            { key: 'space_key', label: 'Default Space Key', type: 'text' },
        ] },
    { key: 'discord', name: 'Discord', category: 'messaging', description: 'Bot e webhooks Discord', fields: [
            { key: 'bot_token', label: 'Bot Token', type: 'password', required: true },
            { key: 'webhook_url', label: 'Webhook URL', type: 'url', placeholder: 'https://discord.com/api/webhooks/...' },
            { key: 'server_id', label: 'Server ID', type: 'text' },
        ] },
    { key: 'eduzz', name: 'Eduzz', category: 'sales', description: 'Plataforma de venda de infoprodutos', fields: [
            { key: 'api_key', label: 'API Key', type: 'password', required: true },
            { key: 'public_key', label: 'Public Key', type: 'password', required: true },
            { key: 'webhook_url', label: 'Webhook URL (receive)', type: 'url', placeholder: 'https://yourserver.com/webhooks/eduzz' },
        ] },
    { key: 'figma', name: 'Figma', category: 'design', description: 'Design de interfaces e handoff para devs', fields: [
            { key: 'access_token', label: 'Personal Access Token', type: 'password', required: true },
            { key: 'team_id', label: 'Team ID', type: 'text' },
            { key: 'default_file_key', label: 'Default File Key', type: 'text' },
        ] },
    { key: 'github', name: 'GitHub', category: 'dev', description: 'Repositórios, issues e pull requests', fields: [
            { key: 'token', label: 'Personal Access Token', type: 'password', required: true, placeholder: 'ghp_...' },
            { key: 'org', label: 'Organization', type: 'text', placeholder: 'my-org' },
            { key: 'default_repo', label: 'Default Repository', type: 'text', placeholder: 'my-repo' },
        ] },
    { key: 'gitlab', name: 'GitLab', category: 'dev', description: 'Repositórios, CI/CD e DevOps', fields: [
            { key: 'token', label: 'Personal Access Token', type: 'password', required: true, placeholder: 'glpat-...' },
            { key: 'base_url', label: 'Base URL', type: 'url', placeholder: 'https://gitlab.com (ou self-hosted)' },
            { key: 'default_project_id', label: 'Default Project ID', type: 'text' },
        ] },
    { key: 'google_ads', name: 'Google Ads', category: 'ads', description: 'Campanhas e anúncios Google', fields: [
            { key: 'client_id', label: 'Client ID', type: 'text', required: true },
            { key: 'client_secret', label: 'Client Secret', type: 'password', required: true },
            { key: 'developer_token', label: 'Developer Token', type: 'password', required: true },
            { key: 'customer_id', label: 'Customer ID', type: 'text', required: true, placeholder: '123-456-7890' },
            { key: 'refresh_token', label: 'Refresh Token', type: 'password', required: true },
        ] },
    { key: 'hotmart', name: 'Hotmart', category: 'sales', description: 'Plataforma de produtos digitais e afiliados', fields: [
            { key: 'client_id', label: 'Client ID', type: 'text', required: true },
            { key: 'client_secret', label: 'Client Secret', type: 'password', required: true },
            { key: 'basic_token', label: 'Basic Token', type: 'password', required: true },
            { key: 'hottok', label: 'Hottok (Webhook Token)', type: 'password', placeholder: 'Token para validar webhooks' },
        ] },
    { key: 'hubspot', name: 'HubSpot', category: 'crm', description: 'CRM, marketing e vendas', fields: [
            { key: 'access_token', label: 'Private App Access Token', type: 'password', required: true, placeholder: 'pat-...' },
            { key: 'portal_id', label: 'Portal ID', type: 'text' },
        ] },
    { key: 'instagram', name: 'Instagram', category: 'ads', description: 'Instagram Business API', fields: [
            { key: 'access_token', label: 'Access Token', type: 'password', required: true },
            { key: 'business_account_id', label: 'Business Account ID', type: 'text', required: true },
        ] },
    { key: 'intercom', name: 'Intercom', category: 'support', description: 'Engajamento e suporte ao cliente', fields: [
            { key: 'access_token', label: 'Access Token', type: 'password', required: true },
            { key: 'app_id', label: 'App ID', type: 'text' },
            { key: 'webhook_secret', label: 'Webhook Secret', type: 'password' },
        ] },
    { key: 'jira', name: 'Jira', category: 'dev', description: 'Gestão de projetos e tickets', fields: [
            { key: 'base_url', label: 'Base URL', type: 'url', required: true, placeholder: 'https://mycompany.atlassian.net' },
            { key: 'email', label: 'Email', type: 'text', required: true, placeholder: 'user@company.com' },
            { key: 'api_token', label: 'API Token', type: 'password', required: true },
            { key: 'project_key', label: 'Default Project Key', type: 'text', placeholder: 'PROJ' },
        ] },
    { key: 'kiwify', name: 'Kiwify', category: 'sales', description: 'Plataforma de venda de cursos e infoprodutos', fields: [
            { key: 'api_key', label: 'API Key', type: 'password', required: true },
            { key: 'webhook_secret', label: 'Webhook Secret', type: 'password', placeholder: 'Para validar webhooks recebidos' },
        ] },
    { key: 'lastlink', name: 'Lastlink', category: 'sales', description: 'Plataforma de monetização e assinaturas', fields: [
            { key: 'api_token', label: 'API Token', type: 'password', required: true },
            { key: 'webhook_url', label: 'Webhook URL (receive)', type: 'url', placeholder: 'https://yourserver.com/webhooks/lastlink' },
        ] },
    { key: 'linear', name: 'Linear', category: 'pm', description: 'Gestão de projetos e issues para times de engenharia', fields: [
            { key: 'api_key', label: 'API Key', type: 'password', required: true, placeholder: 'lin_api_...' },
            { key: 'team_id', label: 'Default Team ID', type: 'text' },
            { key: 'webhook_secret', label: 'Webhook Secret', type: 'password' },
        ] },
    { key: 'mercado_pago', name: 'Mercado Pago', category: 'sales', description: 'Pagamentos, Pix e checkout', fields: [
            { key: 'access_token', label: 'Access Token', type: 'password', required: true, placeholder: 'APP_USR-...' },
            { key: 'public_key', label: 'Public Key', type: 'text', required: true },
            { key: 'webhook_secret', label: 'Webhook Secret', type: 'password' },
        ] },
    { key: 'meta_ads', name: 'Meta Ads', category: 'ads', description: 'Facebook & Instagram Ads Manager', fields: [
            { key: 'access_token', label: 'Access Token', type: 'password', required: true },
            { key: 'ad_account_id', label: 'Ad Account ID', type: 'text', required: true, placeholder: 'act_123456' },
            { key: 'app_id', label: 'App ID', type: 'text', required: true },
            { key: 'app_secret', label: 'App Secret', type: 'password', required: true },
        ] },
    { key: 'movidesk', name: 'Movidesk', category: 'support', description: 'Helpdesk e atendimento ao cliente', fields: [
            { key: 'token', label: 'API Token', type: 'password', required: true },
            { key: 'base_url', label: 'Base URL', type: 'url', placeholder: 'https://mycompany.movidesk.com' },
        ] },
    { key: 'notion', name: 'Notion', category: 'pm', description: 'Docs, wikis e bases de conhecimento', fields: [
            { key: 'api_key', label: 'Integration Token', type: 'password', required: true, placeholder: 'secret_...' },
            { key: 'default_database_id', label: 'Default Database ID', type: 'text' },
        ] },
    { key: 'pipedrive', name: 'Pipedrive', category: 'crm', description: 'CRM e gestão de vendas', fields: [
            { key: 'api_token', label: 'API Token', type: 'password', required: true },
            { key: 'company_domain', label: 'Company Domain', type: 'text', required: true, placeholder: 'mycompany' },
        ] },
    { key: 'rd_station', name: 'RD Station', category: 'crm', description: 'Marketing digital e CRM (líder no Brasil)', fields: [
            { key: 'client_id', label: 'Client ID', type: 'text', required: true },
            { key: 'client_secret', label: 'Client Secret', type: 'password', required: true },
            { key: 'access_token', label: 'Access Token', type: 'password' },
            { key: 'refresh_token', label: 'Refresh Token', type: 'password' },
        ] },
    { key: 'sentry', name: 'Sentry', category: 'monitoring', description: 'Monitoramento de erros e performance', fields: [
            { key: 'dsn', label: 'DSN', type: 'url', required: true, placeholder: 'https://xxx@sentry.io/123' },
            { key: 'auth_token', label: 'Auth Token', type: 'password', required: true },
            { key: 'org', label: 'Organization Slug', type: 'text', required: true },
            { key: 'project', label: 'Project Slug', type: 'text' },
        ] },
    { key: 'slack', name: 'Slack', category: 'messaging', description: 'Comunicação de time e notificações', fields: [
            { key: 'bot_token', label: 'Bot Token', type: 'password', required: true, placeholder: 'xoxb-...' },
            { key: 'signing_secret', label: 'Signing Secret', type: 'password', required: true },
            { key: 'default_channel', label: 'Default Channel', type: 'text', placeholder: '#general' },
            { key: 'webhook_url', label: 'Incoming Webhook URL', type: 'url' },
        ] },
    { key: 'stripe', name: 'Stripe', category: 'sales', description: 'Pagamentos e assinaturas internacionais', fields: [
            { key: 'secret_key', label: 'Secret Key', type: 'password', required: true, placeholder: 'sk_live_...' },
            { key: 'publishable_key', label: 'Publishable Key', type: 'text', required: true, placeholder: 'pk_live_...' },
            { key: 'webhook_secret', label: 'Webhook Secret', type: 'password', placeholder: 'whsec_...' },
        ] },
    { key: 'telegram', name: 'Telegram', category: 'messaging', description: 'Bot de mensagens Telegram', fields: [
            { key: 'bot_token', label: 'Bot Token', type: 'password', required: true, placeholder: '123456:ABC-DEF...' },
            { key: 'default_chat_id', label: 'Default Chat ID', type: 'text', placeholder: '-1001234567890' },
        ] },
    { key: 'vercel', name: 'Vercel', category: 'cloud', description: 'Deploy e hosting de aplicações web', fields: [
            { key: 'token', label: 'API Token', type: 'password', required: true },
            { key: 'team_id', label: 'Team ID', type: 'text' },
            { key: 'project_id', label: 'Default Project ID', type: 'text' },
        ] },
    { key: 'whatsapp', name: 'WhatsApp', category: 'messaging', description: 'Mensagens via WhatsApp Business API (Meta)', fields: [
            { key: 'api_key', label: 'API Key', type: 'password', required: true },
            { key: 'phone_number_id', label: 'Phone Number ID', type: 'text', required: true },
            { key: 'business_account_id', label: 'Business Account ID', type: 'text', required: true },
        ] },
    { key: 'zendesk', name: 'Zendesk', category: 'support', description: 'Helpdesk e atendimento ao cliente', fields: [
            { key: 'subdomain', label: 'Subdomain', type: 'text', required: true, placeholder: 'mycompany' },
            { key: 'email', label: 'Agent Email', type: 'text', required: true },
            { key: 'api_token', label: 'API Token', type: 'password', required: true },
        ] },
];
const PROVIDER_KEYS = new Set(PROVIDER_CATALOG.map((p) => p.key));
/** Mask a secret value — show first 4 and last 2 chars if long enough */
function maskValue(value) {
    if (value.length <= 8)
        return '••••••••';
    return value.slice(0, 4) + '••••' + value.slice(-2);
}
/** Mask all password-type fields in a config object */
function maskConfig(provider, config) {
    const def = PROVIDER_CATALOG.find((p) => p.key === provider);
    if (!def)
        return config;
    const masked = {};
    for (const [k, v] of Object.entries(config)) {
        const field = def.fields.find((f) => f.key === k);
        masked[k] = field?.type === 'password' && v ? maskValue(v) : v;
    }
    return masked;
}
/** Build env key from provider + field: github + token → GITHUB_TOKEN */
function envKey(provider, fieldKey) {
    return `${provider}_${fieldKey}`.toUpperCase();
}
function getEnvPath() {
    return process.env.DOTENV_PATH ?? new URL('../../../.env', import.meta.url).pathname;
}
/** Sync integration config values to .env so agents/squads can read them */
function syncToEnv(provider, config, enabled) {
    try {
        const envPath = getEnvPath();
        const entries = parseEnvFile(envPath);
        const def = PROVIDER_CATALOG.find((p) => p.key === provider);
        if (!def)
            return;
        for (const field of def.fields) {
            const key = envKey(provider, field.key);
            const value = config[field.key];
            if (enabled && value) {
                entries.set(key, value);
                process.env[key] = value;
            }
            else {
                entries.delete(key);
                delete process.env[key];
            }
        }
        writeEnvFile(envPath, entries);
    }
    catch {
        // Non-fatal: env sync failure should not block the API response
    }
}
/** Remove all env keys for a provider */
function removeFromEnv(provider) {
    try {
        const envPath = getEnvPath();
        const entries = parseEnvFile(envPath);
        const def = PROVIDER_CATALOG.find((p) => p.key === provider);
        if (!def)
            return;
        for (const field of def.fields) {
            const key = envKey(provider, field.key);
            entries.delete(key);
            delete process.env[key];
        }
        writeEnvFile(envPath, entries);
    }
    catch {
        // Non-fatal
    }
}
export async function integrationRoutes(app, opts) {
    const { db } = opts;
    // GET /api/integrations/catalog — list available providers with field definitions
    app.get('/api/integrations/catalog', {
        preHandler: [app.requireAuth],
    }, async (_request, reply) => {
        return reply.send({ providers: PROVIDER_CATALOG });
    });
    // GET /api/integrations — list all configured integrations (secrets masked)
    app.get('/api/integrations', {
        preHandler: [app.requireAuth],
    }, async (_request, reply) => {
        const rows = db.prepare('SELECT * FROM integrations ORDER BY provider ASC').all();
        const integrations = rows.map((row) => {
            const config = JSON.parse(row.config);
            return {
                provider: row.provider,
                enabled: row.enabled === 1,
                config: maskConfig(row.provider, config),
                created_at: row.created_at,
                updated_at: row.updated_at,
            };
        });
        return reply.send({ integrations });
    });
    // PATCH /api/integrations/:provider — upsert config for a provider
    app.patch('/api/integrations/:provider', {
        preHandler: [app.requireAuth],
    }, async (request, reply) => {
        const { provider } = request.params;
        if (!PROVIDER_KEYS.has(provider)) {
            return reply.status(400).send({ error: `Unknown provider: ${provider}` });
        }
        const { enabled, config } = request.body;
        const now = new Date().toISOString();
        const existing = db.prepare('SELECT * FROM integrations WHERE provider = ?').get(provider);
        if (existing) {
            // Merge config: keep existing values for fields not provided, and preserve
            // existing secrets when the client sends back masked values (••••)
            const currentConfig = JSON.parse(existing.config);
            let mergedConfig = currentConfig;
            if (config) {
                mergedConfig = { ...currentConfig };
                for (const [k, v] of Object.entries(config)) {
                    // Skip masked values — keep the existing secret
                    if (v && v.includes('••••'))
                        continue;
                    mergedConfig[k] = v;
                }
            }
            db.prepare('UPDATE integrations SET enabled = ?, config = ?, updated_at = ? WHERE provider = ?').run(enabled !== undefined ? (enabled ? 1 : 0) : existing.enabled, JSON.stringify(mergedConfig), now, provider);
        }
        else {
            db.prepare('INSERT INTO integrations (provider, enabled, config, created_at, updated_at) VALUES (?, ?, ?, ?, ?)').run(provider, enabled ? 1 : 0, JSON.stringify(config || {}), now, now);
        }
        const row = db.prepare('SELECT * FROM integrations WHERE provider = ?').get(provider);
        const savedConfig = JSON.parse(row.config);
        // Sync to .env so agents/squads can use these values
        syncToEnv(provider, savedConfig, row.enabled === 1);
        return reply.send({
            integration: {
                provider: row.provider,
                enabled: row.enabled === 1,
                config: maskConfig(row.provider, savedConfig),
                created_at: row.created_at,
                updated_at: row.updated_at,
            },
        });
    });
    // DELETE /api/integrations/:provider — remove an integration
    app.delete('/api/integrations/:provider', {
        preHandler: [app.requireAuth],
    }, async (request, reply) => {
        const { provider } = request.params;
        const result = db.prepare('DELETE FROM integrations WHERE provider = ?').run(provider);
        if (result.changes === 0) {
            return reply.status(404).send({ error: 'Integration not found' });
        }
        // Remove env keys for this provider
        removeFromEnv(provider);
        return reply.send({ ok: true });
    });
}
//# sourceMappingURL=integration-routes.js.map