const express = require('express');
const router = express.Router();
const { getDb } = require('../db');
const { getProviders } = require('../lib/ai');

router.get('/', (req, res) => {
  const db = getDb();
  const aiProviders = getProviders();

  const integrations = [
    { id: 'openrouter', name: 'OpenRouter', description: 'Multi-model AI gateway', icon: 'sparkles', category: 'ai', status: 'available' },
    { id: 'openai', name: 'OpenAI', description: 'GPT-4o, o1 models', icon: 'bot', category: 'ai', status: 'available' },
    { id: 'anthropic', name: 'Anthropic', description: 'Claude models', icon: 'brain', category: 'ai', status: 'available' },
    { id: 'ollama', name: 'Ollama', description: 'Lokale AI modellen', icon: 'cpu', category: 'ai', status: 'available' },
    { id: 'google_calendar', name: 'Google Calendar', description: 'Sync afspraken', icon: 'calendar', category: 'calendar', status: 'available' },
    { id: 'slack', name: 'Slack', description: 'Team notificaties', icon: 'message-square', category: 'comms', status: 'available' },
    { id: 'hubspot', name: 'HubSpot CRM', description: 'Externe CRM sync', icon: 'users', category: 'crm', status: 'available' },
    { id: 'quickbooks', name: 'QuickBooks', description: 'Boekhouding', icon: 'dollar-sign', category: 'finance', status: 'available' }
  ];

  let activeIntegrations = [];
  try {
    activeIntegrations = db.prepare('SELECT * FROM integrations WHERE status = ?').all('active');
  } catch (e) { activeIntegrations = []; }

  res.render('integrations', { integrations, activeIntegrations, aiProviders, saved: req.query.saved });
});

router.post('/connect/:id', (req, res) => {
  const db = getDb();
  const { id } = req.params;
  const { api_key, webhook_url, config } = req.body;

  db.prepare(`
    INSERT OR REPLACE INTO integrations (id, name, api_key, webhook_url, config, status, created_at)
    VALUES (?, ?, ?, ?, ?, 'active', datetime('now'))
  `).run(id, id, api_key || '', webhook_url || '', JSON.stringify(config || {}));

  res.redirect('/integrations?saved=1');
});

router.post('/disconnect/:id', (req, res) => {
  const db = getDb();
  db.prepare('DELETE FROM integrations WHERE id = ?').run(req.params.id);
  res.redirect('/integrations');
});

router.post('/test/:id', (req, res) => {
  res.json({ success: true, message: `Integration ${req.params.id} test successful` });
});

module.exports = router;
