import express from 'express';
import { apiKeysDb, credentialsDb } from '../database/db.js';

const router = express.Router();

// ===============================
// API Keys Management
// ===============================

// Get all API keys for the authenticated user
router.get('/api-keys', async (req, res) => {
  try {
    const apiKeys = await apiKeysDb.getApiKeys(req.user.id);
    // Don't send the full API key in the list for security
    const sanitizedKeys = apiKeys.map(key => ({
      ...key,
      api_key: key.api_key.substring(0, 10) + '...'
    }));
    res.json({ apiKeys: sanitizedKeys });
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch API keys' });
  }
});

// Create a new API key
router.post('/api-keys', async (req, res) => {
  try {
    const { keyName } = req.body;

    if (!keyName || !keyName.trim()) {
      return res.status(400).json({ error: 'Key name is required' });
    }

    const result = await apiKeysDb.createApiKey(req.user.id, keyName.trim());
    res.json({
      success: true,
      apiKey: result
    });
  } catch (error) {
    res.status(500).json({ error: 'Failed to create API key' });
  }
});

// Delete an API key
router.delete('/api-keys/:keyId', async (req, res) => {
  try {
    const { keyId } = req.params;
    const success = await apiKeysDb.deleteApiKey(req.user.id, parseInt(keyId));

    if (success) {
      res.json({ success: true });
    } else {
      res.status(404).json({ error: 'API key not found' });
    }
  } catch (error) {
    res.status(500).json({ error: 'Failed to delete API key' });
  }
});

// Toggle API key active status
router.patch('/api-keys/:keyId/toggle', async (req, res) => {
  try {
    const { keyId } = req.params;
    const { isActive } = req.body;

    if (typeof isActive !== 'boolean') {
      return res.status(400).json({ error: 'isActive must be a boolean' });
    }

    const success = await apiKeysDb.toggleApiKey(req.user.id, parseInt(keyId), isActive);

    if (success) {
      res.json({ success: true });
    } else {
      res.status(404).json({ error: 'API key not found' });
    }
  } catch (error) {
    res.status(500).json({ error: 'Failed to toggle API key' });
  }
});

// ===============================
// Generic Credentials Management
// ===============================

// Get all credentials for the authenticated user (optionally filtered by type)
router.get('/credentials', async (req, res) => {
  try {
    const { type } = req.query;
    const credentials = await credentialsDb.getCredentials(req.user.id, type || null);
    // Don't send the actual credential values for security
    res.json({ credentials });
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch credentials' });
  }
});

// Create a new credential
router.post('/credentials', async (req, res) => {
  try {
    const { credentialName, credentialType, credentialValue, description } = req.body;

    if (!credentialName || !credentialName.trim()) {
      return res.status(400).json({ error: 'Credential name is required' });
    }

    if (!credentialType || !credentialType.trim()) {
      return res.status(400).json({ error: 'Credential type is required' });
    }

    if (!credentialValue || !credentialValue.trim()) {
      return res.status(400).json({ error: 'Credential value is required' });
    }

    const result = await credentialsDb.createCredential(
      req.user.id,
      credentialName.trim(),
      credentialType.trim(),
      credentialValue.trim(),
      description?.trim() || null
    );

    res.json({
      success: true,
      credential: result
    });
  } catch (error) {
    res.status(500).json({ error: 'Failed to create credential' });
  }
});

// Delete a credential
router.delete('/credentials/:credentialId', async (req, res) => {
  try {
    const { credentialId } = req.params;
    const success = await credentialsDb.deleteCredential(req.user.id, parseInt(credentialId));

    if (success) {
      res.json({ success: true });
    } else {
      res.status(404).json({ error: 'Credential not found' });
    }
  } catch (error) {
    res.status(500).json({ error: 'Failed to delete credential' });
  }
});

// Toggle credential active status
router.patch('/credentials/:credentialId/toggle', async (req, res) => {
  try {
    const { credentialId } = req.params;
    const { isActive } = req.body;

    if (typeof isActive !== 'boolean') {
      return res.status(400).json({ error: 'isActive must be a boolean' });
    }

    const success = await credentialsDb.toggleCredential(req.user.id, parseInt(credentialId), isActive);

    if (success) {
      res.json({ success: true });
    } else {
      res.status(404).json({ error: 'Credential not found' });
    }
  } catch (error) {
    res.status(500).json({ error: 'Failed to toggle credential' });
  }
});

// ===============================
// AI Provider Keys (BYOK)
// ===============================

const AI_PROVIDER_TYPES = [
  'anthropic_key',
  'openai_key',
  'openrouter_key',
  'google_key',
];

// Get all AI provider keys for the authenticated user (masked values)
router.get('/ai-providers', async (req, res) => {
  try {
    const allCreds = [];
    for (const type of AI_PROVIDER_TYPES) {
      const creds = await credentialsDb.getCredentials(req.user.id, type);
      allCreds.push(...creds.map(c => ({
        id: c.id,
        credential_name: c.credential_name,
        credential_type: c.credential_type,
        description: c.description,
        is_active: c.is_active,
        created_at: c.created_at,
        // Mask the key — show first 8 and last 4 chars
        masked_value: c.credential_value
          ? c.credential_value.slice(0, 8) + '...' + c.credential_value.slice(-4)
          : '***',
      })));
    }
    res.json({ providers: allCreds });
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch AI provider keys' });
  }
});

// Save an AI provider key
router.post('/ai-providers', async (req, res) => {
  try {
    const { providerType, apiKey, name } = req.body;

    if (!providerType || !AI_PROVIDER_TYPES.includes(providerType)) {
      return res.status(400).json({ error: `Invalid provider type. Supported: ${AI_PROVIDER_TYPES.join(', ')}` });
    }
    if (!apiKey || !apiKey.trim()) {
      return res.status(400).json({ error: 'API key is required' });
    }
    if (apiKey.trim().length < 10 || apiKey.trim().length > 256) {
      return res.status(400).json({ error: 'Invalid API key length' });
    }

    const label = providerType.replace('_key', '').replace('_', ' ');
    const credName = name?.trim() || `${label} API key`;

    // Deactivate existing keys of same type (user should only have one active per provider)
    const existing = await credentialsDb.getCredentials(req.user.id, providerType);
    for (const cred of existing) {
      if (cred.is_active) {
        await credentialsDb.toggleCredential(req.user.id, cred.id, false);
      }
    }

    const result = await credentialsDb.createCredential(
      req.user.id,
      credName,
      providerType,
      apiKey.trim(),
      `User-provided ${label} API key`
    );

    res.json({ success: true, credential: { id: result.id, credential_type: providerType, credential_name: credName } });
  } catch (error) {
    res.status(500).json({ error: 'Failed to save AI provider key' });
  }
});

// Delete an AI provider key
router.delete('/ai-providers/:credentialId', async (req, res) => {
  try {
    const { credentialId } = req.params;
    const success = await credentialsDb.deleteCredential(req.user.id, parseInt(credentialId));
    if (success) {
      res.json({ success: true });
    } else {
      res.status(404).json({ error: 'Provider key not found' });
    }
  } catch (error) {
    res.status(500).json({ error: 'Failed to delete provider key' });
  }
});

export default router;
