/**
 * WordPress Configuration Routes (Per-Tenant — Settings → Integrations)
 *
 * Per-admin WordPress Application Password credential management:
 *   - GET    /        → Get current config (Application Password masked)
 *   - POST   /        → Save/update Site URL, Username, Application Password
 *   - DELETE /        → Remove config (disables integration)
 *   - POST   /test    → Test connection with current credentials
 *   - POST   /toggle  → Enable/disable the integration
 *
 * Each admin manages their own WordPress credentials independently.
 * Credentials are stored in HostingConnection (provider: 'wordpress')
 * with AES-256-GCM encryption and never echoed back in full.
 *
 * Mounted at /api/wordpress/config — so the router paths
 * are relative (no /config prefix to avoid /config/config doubling).
 */

import express, { Request, Response } from 'express';
import { authenticate } from '../middleware/auth';
import {
  getWordPressConfig,
  saveWordPressConfig,
  deleteWordPressConfig,
  testWordPressConnection,
  toggleWordPressEnabled,
} from '../services/wordpress/WordPressConfigService';

const router = express.Router();

// ============================================
// HELPER: Get company ID and user ID from authenticated user
// ============================================

function getCompanyId(req: Request): string | undefined {
  const user = (req as any).user;
  return user?.activeCompanyId || user?.companyIds?.[0];
}

function getUserId(req: Request): string | undefined {
  const user = (req as any).user;
  return user?._id?.toString();
}

// ============================================
// GET CONFIG — Returns masked credentials (safe for frontend)
// ============================================

router.get('/', authenticate, async (req: Request, res: Response) => {
  try {
    const companyId = getCompanyId(req);
    const userId = getUserId(req);
    if (!companyId || !userId) {
      return res.status(400).json({ error: 'Company or user ID not found' });
    }

    const config = await getWordPressConfig(companyId, userId);
    res.json({ data: config });
  } catch (error) {
    console.error('[WordPressConfig] GET / error:', error);
    res.status(500).json({ error: 'Failed to get WordPress configuration' });
  }
});

// ============================================
// SAVE CONFIG — Encrypts Application Password and stores in HostingConnection
// ============================================

router.post('/', authenticate, async (req: Request, res: Response) => {
  try {
    const companyId = getCompanyId(req);
    const userId = getUserId(req);
    if (!companyId || !userId) {
      return res.status(400).json({ error: 'Company or user ID not found' });
    }

    const { siteUrl, username, appPassword, enabled } = req.body;

    if (!siteUrl?.trim()) {
      return res.status(400).json({ error: 'Site URL is required' });
    }
    // Validate that siteUrl is a valid HTTP/HTTPS URL
    try {
      const parsed = new URL(siteUrl.trim());
      if (!['http:', 'https:'].includes(parsed.protocol)) {
        return res.status(400).json({ error: 'Site URL must start with http:// or https://' });
      }
    } catch {
      return res.status(400).json({ error: 'Site URL is not a valid URL. Example: https://yourwordpress.com' });
    }
    if (!username?.trim()) {
      return res.status(400).json({ error: 'Username is required' });
    }
    if (!appPassword?.trim()) {
      return res.status(400).json({ error: 'Application Password is required' });
    }

    const result = await saveWordPressConfig(companyId, userId, {
      siteUrl: siteUrl.trim(),
      username: username.trim(),
      appPassword: appPassword.trim(),
      enabled: enabled !== undefined ? enabled : true,
      updatedBy: userId,
    });

    if (result.success) {
      const config = await getWordPressConfig(companyId, userId);
      res.json({ data: config });
    } else {
      res.status(500).json({ error: result.error || 'Failed to save configuration' });
    }
  } catch (error) {
    console.error('[WordPressConfig] POST / error:', error);
    res.status(500).json({ error: 'Failed to save WordPress configuration' });
  }
});

// ============================================
// DELETE CONFIG — Removes HostingConnection document
// ============================================

router.delete('/', authenticate, async (req: Request, res: Response) => {
  try {
    const companyId = getCompanyId(req);
    const userId = getUserId(req);
    if (!companyId || !userId) {
      return res.status(400).json({ error: 'Company or user ID not found' });
    }

    const result = await deleteWordPressConfig(companyId, userId);

    if (result.success) {
      res.json({ data: { message: 'WordPress configuration removed' } });
    } else {
      res.status(500).json({ error: result.error || 'Failed to delete configuration' });
    }
  } catch (error) {
    console.error('[WordPressConfig] DELETE / error:', error);
    res.status(500).json({ error: 'Failed to delete WordPress configuration' });
  }
});

// ============================================
// TEST CONNECTION — Validates stored credentials
// ============================================

router.post('/test', authenticate, async (req: Request, res: Response) => {
  try {
    const companyId = getCompanyId(req);
    const userId = getUserId(req);
    if (!companyId || !userId) {
      return res.status(400).json({ error: 'Company or user ID not found' });
    }

    const result = await testWordPressConnection(companyId, userId);
    res.json({ data: result });
  } catch (error) {
    console.error('[WordPressConfig] POST /test error:', error);
    res.status(500).json({ error: 'Failed to test connection' });
  }
});

// ============================================
// TOGGLE ENABLED — Enable/disable the integration
// After toggling, re-fetches the full config so the frontend
// gets a complete config object (not just { success, enabled }).
// ============================================

router.post('/toggle', authenticate, async (req: Request, res: Response) => {
  try {
    const companyId = getCompanyId(req);
    const userId = getUserId(req);
    if (!companyId || !userId) {
      return res.status(400).json({ error: 'Company or user ID not found' });
    }

    const { enabled } = req.body;
    if (typeof enabled !== 'boolean') {
      return res.status(400).json({ error: 'enabled must be a boolean' });
    }

    const result = await toggleWordPressEnabled(companyId, userId, enabled);

    if (result.success) {
      // Re-fetch the full config so the frontend gets a complete state
      const config = await getWordPressConfig(companyId, userId);
      res.json({ data: config });
    } else {
      res.status(500).json({ error: result.error || 'Failed to toggle integration' });
    }
  } catch (error) {
    console.error('[WordPressConfig] POST /toggle error:', error);
    res.status(500).json({ error: 'Failed to toggle integration' });
  }
});

export default router;