/**
 * Threads N8n Auth Routes (Social Media OS connectivity)
 *
 * Configuration-based (no OAuth) channel for publishing Threads posts through n8n.
 * Uses the Threads API exclusively.
 *
 * Routes:
 * - GET    /           → Get current config (secrets masked)
 * - POST   /           → Save/update configuration
 * - DELETE /           → Delete configuration (full removal)
 * - POST   /test       → Test connection to the n8n webhook URL
 * - POST   /disconnect → Disconnect (mark as disconnected, keep config)
 *
 * All routes require authentication. The companyId is derived from the authenticated user.
 */

import express, { Request, Response } from 'express';
import { authenticate } from '../middleware/auth';
import {
  getThreadsN8nConfig,
  saveThreadsN8nConfig,
  deleteThreadsN8nConfig,
  disconnectThreadsN8n,
  testThreadsN8nConnection,
} from '../services/threads-n8n/threadsN8nConfigService';

const router = express.Router();

// ============================================
// GET CONFIG — returns masked config (safe for frontend)
// ============================================

router.get('/', authenticate, async (req: Request, res: Response) => {
  try {
    const companyId = (req.user!.activeCompanyId || req.user!.companyIds[0]).toString();
    const config = await getThreadsN8nConfig(companyId);
    res.json(config);
  } catch (error) {
    console.error('[ThreadsN8n] Get config error:', error);
    res.status(500).json({ error: 'Failed to load Threads N8n configuration' });
  }
});

// ============================================
// SAVE CONFIG — creates or updates the configuration
// ============================================

router.post('/', authenticate, async (req: Request, res: Response) => {
  try {
    const companyId = (req.user!.activeCompanyId || req.user!.companyIds[0]).toString();
    const userId = req.user!._id.toString();
    const {
      webhookUrl,
      publishMethod,
      // Threads API fields
      threadsUserId,
      threadsAccessToken,
      appId,
      appSecret,
      // Common
      postType,
    } = req.body;

    // ── Common validation ──
    if (!webhookUrl?.trim()) {
      return res.status(400).json({ error: 'Webhook URL is required' });
    }

    const method: 'graph_api' = publishMethod || 'graph_api';

    if (method !== 'graph_api') {
      return res.status(400).json({ error: 'publishMethod must be "graph_api" for Threads N8n' });
    }

    // ── Threads API validation ──
    if (!threadsUserId?.trim()) {
      return res.status(400).json({ error: 'Threads User ID is required for Graph API method' });
    }
    // threadsAccessToken is required on first save — the service checks if an existing one is stored

    const result = await saveThreadsN8nConfig(companyId, {
      webhookUrl: webhookUrl.trim(),
      publishMethod: method,
      // Threads API fields
      threadsUserId: threadsUserId?.trim(),
      threadsAccessToken: threadsAccessToken?.trim(),
      appId: appId?.trim(),
      appSecret: appSecret?.trim(),
      // Common
      postType: postType || 'text',
      updatedBy: userId,
    });

    if (!result.success) {
      return res.status(400).json({ error: result.error });
    }

    const updatedConfig = await getThreadsN8nConfig(companyId);
    res.json({
      message: 'Threads N8n configuration saved',
      callbackUrl: result.callbackUrl,
      ...updatedConfig,
    });
  } catch (error) {
    console.error('[ThreadsN8n] Save config error:', error);
    res.status(500).json({ error: 'Failed to save Threads N8n configuration' });
  }
});

// ============================================
// DELETE CONFIG — removes configuration entirely
// ============================================

router.delete('/', authenticate, async (req: Request, res: Response) => {
  try {
    const companyId = (req.user!.activeCompanyId || req.user!.companyIds[0]).toString();
    const result = await deleteThreadsN8nConfig(companyId);

    if (!result.success) {
      return res.status(400).json({ error: result.error });
    }

    res.json({ message: 'Threads N8n configuration removed' });
  } catch (error) {
    console.error('[ThreadsN8n] Delete config error:', error);
    res.status(500).json({ error: 'Failed to delete Threads N8n configuration' });
  }
});

// ============================================
// TEST CONNECTION — sends test payload to n8n webhook
// ============================================

router.post('/test', authenticate, async (req: Request, res: Response) => {
  try {
    const companyId = (req.user!.activeCompanyId || req.user!.companyIds[0]).toString();
    const result = await testThreadsN8nConnection(companyId);
    res.json(result);
  } catch (error) {
    console.error('[ThreadsN8n] Test connection error:', error);
    res.status(500).json({ error: 'Failed to test connection' });
  }
});

// ============================================
// DISCONNECT — marks as disconnected (keeps config for reconnection)
// ============================================

router.post('/disconnect', authenticate, async (req: Request, res: Response) => {
  try {
    const companyId = (req.user!.activeCompanyId || req.user!.companyIds[0]).toString();
    const result = await disconnectThreadsN8n(companyId);

    if (!result.success) {
      return res.status(400).json({ error: result.error });
    }

    const config = await getThreadsN8nConfig(companyId);
    res.json({ message: 'Threads N8n disconnected', ...config });
  } catch (error) {
    console.error('[ThreadsN8n] Disconnect error:', error);
    res.status(500).json({ error: 'Failed to disconnect Threads N8n' });
  }
});

export default router;