/**
 * Email Integration Routes
 *
 * API endpoints for connecting/disconnecting email providers.
 * Handles Brevo (API key) and Zoho Campaigns (OAuth 2.0) integrations.
 */

import express, { Request, Response } from 'express';
import { body, validationResult, query } from 'express-validator';
import { authenticate } from '../middleware/auth';
import { requirePermission } from '../middleware/permissions';
import { emailIntegrationService } from '../services/email/EmailIntegrationService';
import { getModels } from '../models';
import { EmailIntegration } from '../models/EmailIntegration';
import { triggerService } from '../services/automation/TriggerService';
import { notificationService } from '../services/notificationService';

const router = express.Router();

// ============================================
// PUBLIC ROUTES (No Authentication Required)
// ============================================

/**
 * GET /api/email-integration/zoho/callback
 * Handle OAuth callback from Zoho.
 * This is a PUBLIC route - called by Zoho after user authorization.
 *
 * Query params:
 * - code: Authorization code from Zoho
 * - location: Data center location from Zoho
 * - state: Base64 encoded state with companyId
 */
router.get(
  '/zoho/callback',
  async (req: Request, res: Response) => {
    try {
      const { code, location, state, error: zohoError, error_description } = req.query;

      // Handle OAuth error from Zoho
      if (zohoError) {
        console.error('Zoho OAuth error:', zohoError, error_description);
        // Redirect to frontend with error
        const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3100';
        res.redirect(`${frontendUrl}/settings/email-integration?error=${encodeURIComponent(zohoError as string)}&error_description=${encodeURIComponent((error_description as string) || '')}`);
        return;
      }

      if (!code || !state) {
        res.status(400).json({ error: 'Missing authorization code or state' });
        return;
      }

      // Decode state to get companyId and dataCenter
      let stateData: { companyId: string; dataCenter: string };
      try {
        stateData = JSON.parse(Buffer.from(state as string, 'base64').toString());
      } catch (e) {
        res.status(400).json({ error: 'Invalid state parameter' });
        return;
      }

      const { companyId, dataCenter } = stateData;

      // Use location from Zoho if available, otherwise use stored dataCenter
      const zohoDataCenter = (location as string) || dataCenter || 'com';

      console.log('[ZohoCallback] Processing OAuth callback for company:', companyId);

      // Connect Zoho (exchange code for tokens)
      const result = await emailIntegrationService.connectZoho(
        code as string,
        zohoDataCenter,
        companyId
      );

      if (!result.success) {
        console.error('[ZohoCallback] Failed to connect Zoho:', result.error);
        const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3100';
        res.redirect(`${frontendUrl}/settings/email-integration?error=${encodeURIComponent(result.error || 'Failed to connect Zoho')}`);
        return;
      }

      console.log('[ZohoCallback] Successfully connected Zoho for company:', companyId);

      // Redirect to frontend with success
      const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3100';
      res.redirect(`${frontendUrl}/settings/email-integration?success=zoho_connected`);
    } catch (error: any) {
      console.error('[ZohoCallback] Error processing callback:', error);
      const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3100';
      res.redirect(`${frontendUrl}/settings/email-integration?error=${encodeURIComponent(error.message || 'Failed to complete OAuth flow')}`);
    }
  }
);

// ============================================
// PROTECTED ROUTES (Authentication Required)
// ============================================

router.use(authenticate);

// ============================================
// CONNECTION ROUTES
// ============================================

/**
 * POST /api/email-integration/connect
 * Connect a Brevo account using API key.
 */
router.post(
  '/connect',
  requirePermission('newsletter-content-os', 'edit'),
  [body('apiKey').isString().notEmpty().withMessage('API key is required')],
  async (req: Request, res: Response) => {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        res.status(400).json({ errors: errors.array() });
        return;
      }

      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const { apiKey } = req.body;

      const result = await emailIntegrationService.connectBrevo(companyId, apiKey);

      if (!result.success) {
        res.status(400).json({ error: result.error });
        return;
      }

      res.json({
        success: true,
        integration: {
          provider: result.integration!.provider,
          status: result.integration!.status,
          accountEmail: result.integration!.accountEmail,
          accountName: result.integration!.accountName,
        },
      });
    } catch (error: any) {
      console.error('Failed to connect Brevo:', error);
      res.status(500).json({ error: 'Failed to connect email provider' });
    }
  }
);

/**
 * POST /api/email-integration/connect/mailchimp
 * Connect a Mailchimp account using API key.
 */
router.post(
  '/connect/mailchimp',
  requirePermission('newsletter-content-os', 'edit'),
  [body('apiKey').isString().notEmpty().withMessage('API key is required')],
  async (req: Request, res: Response) => {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        res.status(400).json({ errors: errors.array() });
        return;
      }

      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const { apiKey } = req.body;
      console.log('[Mailchimp] Connection attempt for company:', companyId);

      const result = await emailIntegrationService.connectMailchimp(companyId, apiKey);

      if (!result.success) {
        res.status(400).json({ error: result.error });
        return;
      }

      res.json({
        success: true,
        integration: {
          provider: result.integration!.provider,
          status: result.integration!.status,
          accountEmail: result.integration!.accountEmail,
          accountName: result.integration!.accountName,
        },
      });
    } catch (error: any) {
      console.error('Failed to connect Mailchimp:', error);
      res.status(500).json({ error: 'Failed to connect Mailchimp' });
    }
  }
);

/**
 * POST /api/email-integration/disconnect
 * Disconnect an email integration.
 * Query params:
 * - provider: Optional. If specified, only disconnect that provider.
 */
router.post('/disconnect', async (req: Request, res: Response) => {
  try {
    const companyId = req.user!.companyIds[0];
    if (!companyId) {
      res.status(400).json({ error: 'No company associated with user' });
      return;
    }

    const { provider } = req.query;
    await emailIntegrationService.disconnect(companyId, provider as string);
    res.json({ success: true });
  } catch (error: any) {
    console.error('Failed to disconnect:', error);
    res.status(500).json({ error: 'Failed to disconnect email provider' });
  }
});

/**
 * GET /api/email-integration/connections
 * Get all connected email providers for the current company.
 */
router.get('/connections', async (req: Request, res: Response) => {
  try {
    const companyId = req.user!.companyIds[0];
    if (!companyId) {
      res.status(400).json({ error: 'No company associated with user' });
      return;
    }

    const connections = await emailIntegrationService.getConnections(companyId);
    res.json({ connections });
  } catch (error: any) {
    console.error('Failed to get connections:', error);
    res.status(500).json({ error: 'Failed to get connections' });
  }
});

/**
 * GET /api/email-integration/status
 * Get current integration status.
 */
router.get('/status', async (req: Request, res: Response) => {
  try {
    const companyId = req.user!.companyIds[0];
    if (!companyId) {
      res.status(400).json({ error: 'No company associated with user' });
      return;
    }

    const status = await emailIntegrationService.getStatus(companyId);
    res.json(status);
  } catch (error: any) {
    console.error('Failed to get status:', error);
    res.status(500).json({ error: 'Failed to get integration status' });
  }
});

/**
 * POST /api/email-integration/verify
 * Verify the current connection.
 */
router.post('/verify', async (req: Request, res: Response) => {
  try {
    const companyId = req.user!.companyIds[0];
    if (!companyId) {
      res.status(400).json({ error: 'No company associated with user' });
      return;
    }

    const result = await emailIntegrationService.verifyConnection(companyId);
    res.json(result);
  } catch (error: any) {
    console.error('Failed to verify:', error);
    res.status(500).json({ error: 'Failed to verify connection' });
  }
});

// ============================================
// SENDERS ROUTES
// ============================================

/**
 * GET /api/email-integration/senders
 * Get verified senders from email provider.
 * Query params:
 * - provider: Optional. Specify which provider to use (brevo, zoho, etc.)
 */
router.get('/senders', async (req: Request, res: Response) => {
  try {
    const companyId = req.user!.companyIds[0];
    if (!companyId) {
      res.status(400).json({ error: 'No company associated with user' });
      return;
    }

    // Get provider from query param, or use first connected provider that supports senders
    const requestedProvider = req.query.provider as string | undefined;
    console.log('[Senders Route] Request received - companyId:', companyId, 'requestedProvider:', requestedProvider);

    // If no provider specified, try to find a connected Brevo integration first
    // (since Brevo has full sender management API)
    let provider;
    if (!requestedProvider) {
      // Try Brevo first, then fall back to any connected provider
      provider = await emailIntegrationService.getProvider(companyId, 'brevo');
      if (!provider) {
        provider = await emailIntegrationService.getProvider(companyId);
      }
    } else {
      console.log('[Senders Route] Getting provider for:', requestedProvider);
      provider = await emailIntegrationService.getProvider(companyId, requestedProvider);
    }

    if (!provider) {
      console.log('[Senders Route] No provider found for companyId:', companyId, 'requestedProvider:', requestedProvider);
      res.status(400).json({ error: 'Email provider not connected' });
      return;
    }

    console.log('[Senders Route] Provider found, fetching senders...');
    const senders = await provider.getSenders();
    console.log('[Senders Route] Successfully fetched', senders.length, 'senders');
    res.json(senders);
  } catch (error: any) {
    console.error('[Senders Route] Failed to get senders:', error.message || error);
    console.error('[Senders Route] Error stack:', error.stack);

    // Check for authentication errors (invalid/expired API key)
    const errorMessage = error.message || '';
    const statusCode = error.status || error.statusCode || 500;

    if (statusCode === 401 || errorMessage.includes('unauthorized') || errorMessage.includes('Key not found') || errorMessage.includes('Invalid API key')) {
      // Mark the integration as having an error
      try {
        const companyId = req.user!.companyIds[0];
        const requestedProvider = req.query.provider as string || 'brevo';
        await emailIntegrationService.markConnectionError(companyId, requestedProvider, 'API key is invalid or expired. Please reconnect your account.');
      } catch (updateError) {
        console.error('[Senders Route] Failed to mark connection error:', updateError);
      }

      res.status(401).json({
        error: 'Your API key is invalid or expired',
        details: 'Please disconnect and reconnect your ' + (req.query.provider || 'Brevo') + ' account with a valid API key.',
        needsReconnect: true
      });
      return;
    }

    res.status(500).json({ error: 'Failed to get senders', details: error.message });
  }
});

/**
 * POST /api/email-integration/senders
 * Create a new sender.
 */
router.post(
  '/senders',
  requirePermission('newsletter-content-os', 'create'),
  [body('name').isString().notEmpty(), body('email').isEmail()],
  async (req: Request, res: Response) => {
    try {
      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const provider = await emailIntegrationService.getProvider(companyId);
      if (!provider) {
        res.status(400).json({ error: 'Email provider not connected' });
        return;
      }

      const { name, email } = req.body;
      const sender = await provider.createSender({ name, email });
      res.status(201).json(sender);
    } catch (error: any) {
      console.error('Failed to create sender:', error);
      res.status(500).json({ error: 'Failed to create sender' });
    }
  }
);

// ============================================
// LISTS ROUTES
// ============================================

/**
 * GET /api/email-integration/lists
 * Get contact lists from email provider (Brevo or Zoho).
 * Query params:
 * - provider: Optional. Specify which provider to use (brevo, zoho, etc.)
 */
router.get('/lists', async (req: Request, res: Response) => {
  // Prevent caching - always return fresh data
  res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
  res.setHeader('Pragma', 'no-cache');
  res.setHeader('Expires', '0');

  try {
    const companyId = req.user!.companyIds[0];
    if (!companyId) {
      console.log('[EmailIntegration] No company associated with user');
      res.status(400).json({ error: 'No company associated with user' });
      return;
    }

    const requestedProvider = req.query.provider as string | undefined;
    console.log('[EmailIntegration] Getting lists for company:', companyId, 'provider:', requestedProvider || 'any');

    const provider = await emailIntegrationService.getProvider(companyId, requestedProvider);

    if (!provider) {
      console.log('[EmailIntegration] No provider connected for company:', companyId);
      res.status(400).json({ error: 'Email provider not connected' });
      return;
    }

    console.log('[EmailIntegration] Provider found, fetching lists...');
    const lists = await provider.getLists();
    console.log('[EmailIntegration] Retrieved', lists.length, 'lists:', JSON.stringify(lists).slice(0, 500));
    res.json(lists);
  } catch (error: any) {
    console.error('[EmailIntegration] Failed to get lists:', error.message, error.stack);

    // Check for authentication errors (invalid/expired API key)
    const errorMessage = error.message || '';
    const statusCode = error.status || error.statusCode || 500;

    if (statusCode === 401 || errorMessage.includes('unauthorized') || errorMessage.includes('Key not found') || errorMessage.includes('Invalid API key')) {
      // Mark the integration as having an error
      try {
        const companyId = req.user!.companyIds[0];
        const requestedProvider = req.query.provider as string || 'brevo';
        await emailIntegrationService.markConnectionError(companyId, requestedProvider, 'API key is invalid or expired. Please reconnect your account.');
      } catch (updateError) {
        console.error('[EmailIntegration] Failed to mark connection error:', updateError);
      }

      res.status(401).json({
        error: 'Your API key is invalid or expired',
        details: 'Please disconnect and reconnect your ' + (req.query.provider || 'Brevo') + ' account with a valid API key.',
        needsReconnect: true
      });
      return;
    }

    res.status(500).json({ error: 'Failed to get lists', details: error.message });
  }
});

/**
 * POST /api/email-integration/lists
 * Create a new contact list.
 */
router.post(
  '/lists',
  requirePermission('newsletter-content-os', 'create'),
  [body('name').isString().notEmpty().withMessage('List name is required')],
  async (req: Request, res: Response) => {
    try {
      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      console.log('[EmailIntegration] Creating list for company:', companyId, 'name:', req.body.name);

      const integration = await EmailIntegration.findOne({ companyId });
      const providerName = integration?.provider || 'brevo';

      const provider = await emailIntegrationService.getProvider(companyId);

      if (!provider) {
        console.log('[EmailIntegration] No provider found for company:', companyId);
        res.status(400).json({ error: 'Email provider not connected' });
        return;
      }

      // Get integration to access default sender info
      const defaultSenderEmail = integration?.defaultSenderEmail;
      const defaultSenderName = integration?.defaultSenderName;

      // Get account info for sender fallback
      let accountEmail = integration?.accountEmail || '';
      let accountName = integration?.accountName || '';

      // Build list data with all available fields
      const listData = {
        name: req.body.name,
        senderName: req.body.senderName || defaultSenderName || accountName || 'Newsletter',
        senderEmail: req.body.senderEmail || defaultSenderEmail || accountEmail,
        company: req.body.company,
        address: req.body.address,
        city: req.body.city,
        state: req.body.state,
        zip: req.body.zip,
        country: req.body.country,
      };

      const list = await provider.createList(listData);
      console.log('[EmailIntegration] List created successfully:', list);
      res.status(201).json(list);
    } catch (error: any) {
      console.error('[EmailIntegration] Failed to create list:', error);
      console.error('[EmailIntegration] Error details:', {
        message: error.message,
        stack: error.stack,
        response: error.response?.data,
      });

      // Check for permission errors (403 Forbidden)
      const statusCode = error.status || error.response?.status || 500;
      const errorBody = error.response?.body || error.response?.data || {};

      // Provide user-friendly error messages
      if (statusCode === 403 || errorBody?.status === 403 || errorBody?.title === 'User action not permitted') {
        const providerName = req.query.provider || 'email provider';
        return res.status(403).json({
          error: 'Permission denied',
          details: `Your ${providerName} API key does not have permission to create lists. Please check your API key permissions or upgrade your plan.`,
          helpUrl: 'https://mailchimp.com/help/about-api-keys/',
          permissionError: true,
          provider: providerName,
        });
      }

      // Generic error
      res.status(500).json({
        error: 'Failed to create list',
        details: error.message || 'Unknown error'
      });
    }
  }
);

// ============================================
// CONTACTS ROUTES
// ============================================

/**
 * GET /api/email-integration/lists/:listId/contacts
 * Get contacts from a specific list.
 */
router.get(
  '/lists/:listId/contacts',
  async (req: Request, res: Response) => {
    try {
      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const { listId } = req.params;
      const provider = req.query.provider as string | undefined;

      console.log('[EmailIntegration] Getting contacts for list:', listId, 'provider:', provider);

      const emailProvider = await emailIntegrationService.getProvider(companyId, provider);

      if (!emailProvider) {
        res.status(400).json({ error: 'Email provider not connected' });
        return;
      }

      // Check if provider supports getListMembers
      if (emailProvider.getListMembers) {
        const result = await emailProvider.getListMembers(listId, 100, 0);
        res.json({
          contacts: result.members,
          total: result.total,
          listId,
          provider: provider || 'default',
        });
      } else {
        // Provider doesn't support listing members
        res.json({
          contacts: [],
          total: 0,
          listId,
          provider: provider || 'default',
          message: 'This provider does not support listing contacts. Please use the provider\'s dashboard to view contacts.',
        });
      }
    } catch (error: any) {
      console.error('[EmailIntegration] Failed to get contacts:', error);

      // Check for permission errors (403 Forbidden)
      const statusCode = error.status || error.response?.status || 500;
      const errorBody = error.response?.body || error.response?.data || {};

      if (statusCode === 403 || errorBody?.status === 403 || errorBody?.title === 'User action not permitted') {
        const providerName = req.query.provider || 'email provider';
        return res.status(403).json({
          error: 'Permission denied',
          details: `Your ${providerName} API key does not have permission to view contacts. Please check your API key permissions.`,
          helpUrl: 'https://mailchimp.com/help/about-api-keys/',
          permissionError: true,
          provider: providerName,
        });
      }

      res.status(500).json({
        error: 'Failed to get contacts',
        details: error.message || 'Unknown error'
      });
    }
  }
);

/**
 * POST /api/email-integration/lists/:listId/contacts
 * Add a contact to a specific list.
 */
router.post(
  '/lists/:listId/contacts',
  [
    body('email').isEmail().withMessage('Valid email is required'),
  ],
  async (req: Request, res: Response) => {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        res.status(400).json({ error: 'Invalid email address', details: errors.array() });
        return;
      }

      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const { listId } = req.params;
      const { email, attributes } = req.body;
      const provider = req.query.provider as string | undefined;

      console.log('[EmailIntegration] Adding contact to list:', listId, 'email:', email, 'provider:', provider, 'attributes:', attributes);

      const emailProvider = await emailIntegrationService.getProvider(companyId, provider);

      if (!emailProvider) {
        res.status(400).json({ error: 'Email provider not connected' });
        return;
      }

      // Check if provider supports adding contact with data (Mailchimp supports merge fields)
      if (emailProvider.addContactToListWithData && attributes && Object.keys(attributes).length > 0) {
        // Use the extended method that supports merge fields
        await emailProvider.addContactToListWithData(listId, {
          email,
          firstName: attributes.FNAME || attributes.firstName,
          lastName: attributes.LNAME || attributes.lastName,
          phone: attributes.PHONE || attributes.phone,
          company: attributes.COMPANY || attributes.company,
          address: attributes.ADDRESS || attributes.address,
          city: attributes.CITY || attributes.city,
          state: attributes.STATE || attributes.state,
          zip: attributes.ZIP || attributes.zip,
          country: attributes.COUNTRY || attributes.country,
          birthday: attributes.BIRTHDAY || attributes.birthday,
        });
      } else {
        // Fallback to basic method
        await emailProvider.addContactsToList(listId, [email]);
      }

      res.status(201).json({
        success: true,
        message: `Added ${email} to the list`,
        email,
        listId,
      });

      // Fire automation trigger: contact subscribed to list (non-blocking)
      // Pass listId and provider so workflows can match specific lists
      triggerService.processTrigger({
        type: 'trigger_subscribed',
        companyId,
        contact: { id: email, email, firstName: attributes?.FNAME || attributes?.firstName, lastName: attributes?.LNAME || attributes?.lastName },
        data: { listId: String(listId), provider: provider || undefined },
        timestamp: new Date(),
      })
        .then((matches) => {
          if (matches.length > 0) {
            console.log(`[EmailIntegration] Triggered ${matches.length} workflow(s) for ${email} in list ${listId}`);
          }
        })
        .catch((triggerErr: any) => {
          console.warn('[EmailIntegration] Failed to fire automation trigger:', triggerErr.message);
        });
    } catch (error: any) {
      console.error('[EmailIntegration] Failed to add contact:', error);

      // Check for permission errors (403 Forbidden)
      const statusCode = error.status || error.response?.status || 500;
      const errorBody = error.response?.body || error.response?.data || {};

      if (statusCode === 403 || errorBody?.status === 403 || errorBody?.title === 'User action not permitted') {
        const providerName = req.query.provider || 'email provider';
        return res.status(403).json({
          error: 'Permission denied',
          details: `Your ${providerName} API key does not have permission to add contacts. Please check your API key permissions or upgrade your plan.`,
          helpUrl: 'https://mailchimp.com/help/about-api-keys/',
          permissionError: true,
          provider: providerName,
        });
      }

      res.status(500).json({
        error: 'Failed to add contact',
        details: error.message || 'Unknown error'
      });
    }
  }
);

/**
 * DELETE /api/email-integration/lists/:listId/contacts/:email
 * Remove a contact from a specific list.
 */
router.delete(
  '/lists/:listId/contacts/:email',
  async (req: Request, res: Response) => {
    try {
      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const { listId, email } = req.params;
      const provider = req.query.provider as string | undefined;

      console.log('[EmailIntegration] Removing contact from list:', listId, 'email:', email, 'provider:', provider);

      const emailProvider = await emailIntegrationService.getProvider(companyId, provider);

      if (!emailProvider) {
        res.status(400).json({ error: 'Email provider not connected' });
        return;
      }

      // Remove contact from the list - pass listId as-is (can be string for Mailchimp or number for Brevo)
      await emailProvider.removeContactsFromList(listId, [email]);

      res.json({
        success: true,
        message: `Removed ${email} from the list`,
        email,
        listId,
      });
    } catch (error: any) {
      console.error('[EmailIntegration] Failed to remove contact:', error);

      // Check for permission errors (403 Forbidden)
      const statusCode = error.status || error.response?.status || 500;
      const errorBody = error.response?.body || error.response?.data || {};

      if (statusCode === 403 || errorBody?.status === 403 || errorBody?.title === 'User action not permitted') {
        const providerName = req.query.provider || 'email provider';
        return res.status(403).json({
          error: 'Permission denied',
          details: `Your ${providerName} API key does not have permission to remove contacts. Please check your API key permissions or upgrade your plan.`,
          helpUrl: 'https://mailchimp.com/help/about-api-keys/',
          permissionError: true,
          provider: providerName,
        });
      }

      res.status(500).json({
        error: 'Failed to remove contact',
        details: error.message || 'Unknown error'
      });
    }
  }
);

// ============================================
// CAMPAIGNS ROUTES
// ============================================

// In-memory store for temporary campaign content (for Zoho workaround)
// In production, use Redis or database
const campaignContentStore = new Map<string, { html: string; createdAt: Date }>();

// Clean up old content every 10 minutes
setInterval(() => {
  const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
  for (const [key, value] of campaignContentStore.entries()) {
    if (value.createdAt < oneHourAgo) {
      campaignContentStore.delete(key);
    }
  }
}, 10 * 60 * 1000);

/**
 * GET /api/email-integration/campaign-content/:id
 * Serve campaign HTML content (workaround for Zoho's content_url requirement)
 */
router.get(
  '/campaign-content/:id',
  async (req: Request, res: Response) => {
    const { id } = req.params;
    const content = campaignContentStore.get(id);

    if (!content) {
      res.status(404).send('Campaign content not found or expired');
      return;
    }

    res.setHeader('Content-Type', 'text/html; charset=utf-8');
    res.send(content.html);
  }
);

/**
 * POST /api/email-integration/campaigns/sync
 * Sync a newsletter campaign to email provider (Brevo, Zoho, or Mailchimp).
 * Body params:
 * - newsletterCampaignId: string (required)
 * - campaignData: object (required)
 * - provider: 'brevo' | 'zoho' | 'mailchimp' (optional - if not specified, uses first connected provider)
 */
router.post(
  '/campaigns/sync',
  requirePermission('newsletter-content-os', 'edit'),
  async (req: Request, res: Response) => {
    try {
      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const { newsletterCampaignId, campaignData, provider: requestedProvider } = req.body;

      if (!newsletterCampaignId || !campaignData) {
        res.status(400).json({ error: 'newsletterCampaignId and campaignData are required' });
        return;
      }

      console.log('[EmailIntegration] Syncing campaign for company:', companyId);
      console.log('[EmailIntegration] Newsletter campaign ID:', newsletterCampaignId);
      console.log('[EmailIntegration] Requested provider:', requestedProvider || 'auto');
      console.log('[EmailIntegration] Campaign data:', {
        subject: campaignData.subject,
        senderEmail: campaignData.senderEmail,
        listIds: campaignData.listIds,
      });

      const provider = await emailIntegrationService.getProvider(companyId, requestedProvider);
      if (!provider) {
        res.status(400).json({ error: 'Email provider not connected' });
        return;
      }

      // Get provider type for response
      const status = await emailIntegrationService.getStatus(companyId);
      const providerType = requestedProvider || status?.provider || 'unknown';

      console.log('[EmailIntegration] Using provider:', providerType);

      // For Zoho, we need to handle content_url differently
      // Zoho doesn't accept data: URLs, only public HTTP/HTTPS URLs
      // For local development, campaigns will be created as drafts without content
      let htmlContent = campaignData.htmlContent;
      let htmlUrl = campaignData.htmlUrl;

      if (providerType === 'zoho' && htmlContent && !htmlUrl) {
        // Check if we have a public URL configured
        const publicUrl = process.env.PUBLIC_URL || process.env.BACKEND_URL;

        if (publicUrl && !publicUrl.includes('localhost')) {
          // We have a public URL, create a temporary endpoint
          const contentId = `${newsletterCampaignId}-${Date.now()}`;
          campaignContentStore.set(contentId, { html: htmlContent, createdAt: new Date() });
          htmlUrl = `${publicUrl}/api/email-integration/campaign-content/${contentId}`;
          htmlContent = undefined;
          console.log('[EmailIntegration] Using public URL for Zoho content:', htmlUrl);
        } else {
          // No public URL available - campaign will be created as draft without content
          console.warn('[EmailIntegration] No public URL available for Zoho content');
          console.warn('[EmailIntegration] Campaign will be created as draft without content');
          console.warn('[EmailIntegration] Set PUBLIC_URL or BACKEND_URL environment variable for full content sync');
        }
      }

      // Create campaign in email provider (Brevo or Zoho)
      const result = await provider.createCampaign({
        name: campaignData.name || campaignData.subject,
        subject: campaignData.subject,
        htmlContent: htmlContent,
        htmlUrl: htmlUrl,
        sender: {
          email: campaignData.senderEmail,
          name: campaignData.senderName,
        },
        recipients: campaignData.listIds
          ? { listIds: campaignData.listIds }
          : undefined,
        scheduledAt: campaignData.scheduledAt
          ? new Date(campaignData.scheduledAt)
          : undefined,
      });

      console.log('[EmailIntegration] Campaign created successfully:', result);

      // Store sync record
      const { EmailCampaign } = getModels();

      // Build update object with provider-specific fields
      const updateData: any = {
        companyId,
        newsletterCampaignId,
        provider: providerType,
        providerCampaignId: String(result.campaignId),
        brevoCampaignId: result.campaignId, // Keep for backward compatibility
        syncStatus: 'synced',
        lastSyncedAt: new Date(),
        subject: campaignData.subject,
        senderEmail: campaignData.senderEmail,
        senderName: campaignData.senderName,
        listIds: campaignData.listIds || [],
      };

      // Store provider-specific campaign ID
      if (providerType === 'mailchimp') {
        updateData.mailchimpCampaignId = result.campaignId;
      }

      await EmailCampaign.findOneAndUpdate(
        { companyId, newsletterCampaignId },
        { $set: updateData },
        { upsert: true, new: true }
      );

      // Update last campaign sync timestamp
      await emailIntegrationService.updateLastCampaignSync(companyId);

      // Check if this is a Zoho campaign without content (draft only)
      const isDraftOnly = providerType === 'zoho' && campaignData.htmlContent && !htmlUrl;

      res.json({
        success: true,
        campaignId: result.campaignId,
        brevoCampaignId: result.campaignId, // Keep for backward compatibility
        provider: providerType,
        warning: isDraftOnly
          ? 'Campaign created as draft without content. Zoho requires a public URL for content. Please edit the campaign in Zoho Campaigns to add content, or configure PUBLIC_URL/BACKEND_URL in your environment.'
          : undefined,
      });
    } catch (error: any) {
      console.error('[EmailIntegration] Failed to sync campaign:', error);
      console.error('[EmailIntegration] Error details:', {
        message: error.message,
        stack: error.stack,
        response: error.response?.data,
      });
      res.status(500).json({ error: 'Failed to sync campaign to email provider', details: error.message });
    }
  }
);

/**
 * POST /api/email-integration/campaigns/:id/send
 * Send a synced campaign.
 */
router.post(
  '/campaigns/:id/send',
  requirePermission('newsletter-content-os', 'edit'),
  async (req: Request, res: Response) => {
    try {
      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const { id } = req.params;

      const provider = await emailIntegrationService.getProvider(companyId);
      if (!provider) {
        res.status(400).json({ error: 'Email provider not connected' });
        return;
      }

      const { EmailCampaign } = getModels();
      const campaign = await EmailCampaign.findOne({
        _id: id,
        companyId,
      });

      if (!campaign || !campaign.brevoCampaignId) {
        res.status(404).json({ error: 'Campaign not found or not synced' });
        return;
      }

      await provider.sendCampaign(campaign.brevoCampaignId);

      campaign.syncStatus = 'sent';
      await campaign.save();

      // The provider has accepted the send — the point the registry's
      // `newsletter.campaign.sent` describes. Raised here rather than in the
      // provider services because both Brevo and Zoho funnel through this
      // endpoint, the same reasoning the social publish worker uses to cover
      // eight platforms from one hook. Fire-and-forget: notificationService
      // never throws, so it cannot turn a completed send into a 500.
      void notificationService.notifyUser(String(req.user!._id), {
        type: 'newsletter.campaign.sent',
        message: `"${campaign.subject || 'Your newsletter'}" was sent.`,
        organizationId: companyId,
        entityType: 'email-campaign',
        entityId: String(campaign._id),
        actionUrl: '/newsletter-content-os',
        notifyActor: true,
      });

      res.json({ success: true });
    } catch (error: any) {
      console.error('Failed to send campaign:', error);

      // The other half of the same pair: a send that did not go out is exactly
      // what `newsletter.campaign.failed` is registered for, and it is the one
      // outcome nobody is watching the screen for.
      void notificationService.notifyUser(String(req.user!._id), {
        type: 'newsletter.campaign.failed',
        message: `The newsletter could not be sent: ${error?.message || 'the provider rejected the request'}.`,
        organizationId: req.user!.companyIds?.[0] || null,
        entityType: 'email-campaign',
        entityId: String(req.params.id),
        actionUrl: '/newsletter-content-os',
        notifyActor: true,
      });

      res.status(500).json({ error: 'Failed to send campaign' });
    }
  }
);

/**
 * POST /api/email-integration/campaigns/:id/schedule
 * Schedule a synced campaign.
 */
router.post(
  '/campaigns/:id/schedule',
  requirePermission('newsletter-content-os', 'edit'),
  [body('scheduledAt').isISO8601().withMessage('Valid scheduledAt date is required')],
  async (req: Request, res: Response) => {
    try {
      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const { id } = req.params;
      const { scheduledAt } = req.body;

      const provider = await emailIntegrationService.getProvider(companyId);
      if (!provider) {
        res.status(400).json({ error: 'Email provider not connected' });
        return;
      }

      const { EmailCampaign } = getModels();
      const campaign = await EmailCampaign.findOne({
        _id: id,
        companyId,
      });

      if (!campaign || !campaign.brevoCampaignId) {
        res.status(404).json({ error: 'Campaign not found or not synced' });
        return;
      }

      await provider.scheduleCampaign(campaign.brevoCampaignId, new Date(scheduledAt));

      campaign.syncStatus = 'scheduled';
      await campaign.save();

      res.json({ success: true });
    } catch (error: any) {
      console.error('Failed to schedule campaign:', error);
      res.status(500).json({ error: 'Failed to schedule campaign' });
    }
  }
);

/**
 * POST /api/email-integration/campaigns/:id/test
 * Send test email for a campaign.
 */
router.post(
  '/campaigns/:id/test',
  requirePermission('newsletter-content-os', 'edit'),
  [body('email').isEmail().withMessage('Valid email is required')],
  async (req: Request, res: Response) => {
    try {
      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const { id } = req.params;
      const { email } = req.body;

      const provider = await emailIntegrationService.getProvider(companyId);
      if (!provider) {
        res.status(400).json({ error: 'Email provider not connected' });
        return;
      }

      const { EmailCampaign } = getModels();
      const campaign = await EmailCampaign.findOne({
        _id: id,
        companyId,
      });

      if (!campaign || !campaign.brevoCampaignId) {
        res.status(404).json({ error: 'Campaign not found or not synced' });
        return;
      }

      await provider.sendTestEmail(campaign.brevoCampaignId, email);

      res.json({ success: true });
    } catch (error: any) {
      console.error('Failed to send test email:', error);
      res.status(500).json({ error: 'Failed to send test email' });
    }
  }
);

/**
 * GET /api/email-integration/campaigns/:id/stats
 * Get campaign statistics from Brevo.
 */
router.get('/campaigns/:id/stats', async (req: Request, res: Response) => {
  try {
    const companyId = req.user!.companyIds[0];
    if (!companyId) {
      res.status(400).json({ error: 'No company associated with user' });
      return;
    }

    const { id } = req.params;

    const provider = await emailIntegrationService.getProvider(companyId);
    if (!provider) {
      res.status(400).json({ error: 'Email provider not connected' });
      return;
    }

    const { EmailCampaign } = getModels();
    const campaign = await EmailCampaign.findOne({
      _id: id,
      companyId,
    });

    if (!campaign || !campaign.brevoCampaignId) {
      res.status(404).json({ error: 'Campaign not found or not synced' });
      return;
    }

    const brevoCampaign = await provider.getCampaign(campaign.brevoCampaignId);

    // Update cached stats
    if (brevoCampaign.stats) {
      campaign.stats = brevoCampaign.stats;
      await campaign.save();
    }

    res.json({
      status: brevoCampaign.status,
      stats: brevoCampaign.stats || campaign.stats,
    });
  } catch (error: any) {
    console.error('Failed to get stats:', error);
    res.status(500).json({ error: 'Failed to get campaign statistics' });
  }
});

/**
 * GET /api/email-integration/campaigns
 * Get all synced campaigns for a company.
 */
router.get('/campaigns', async (req: Request, res: Response) => {
  try {
    const companyId = req.user!.companyIds[0];
    if (!companyId) {
      res.status(400).json({ error: 'No company associated with user' });
      return;
    }

    const { EmailCampaign } = getModels();
    const campaigns = await EmailCampaign.find({ companyId }).sort({ createdAt: -1 });

    res.json(campaigns);
  } catch (error: any) {
    console.error('Failed to get campaigns:', error);
    res.status(500).json({ error: 'Failed to get campaigns' });
  }
});

/**
 * DELETE /api/email-integration/campaigns/:id
 * Delete a synced campaign (local only, doesn't delete from Brevo).
 */
router.delete(
  '/campaigns/:id',
  requirePermission('newsletter-content-os', 'delete'),
  async (req: Request, res: Response) => {
    try {
      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const { id } = req.params;

      const { EmailCampaign } = getModels();
      const result = await EmailCampaign.deleteOne({ _id: id, companyId });

      if (result.deletedCount === 0) {
        res.status(404).json({ error: 'Campaign not found' });
        return;
      }

      res.json({ success: true });
    } catch (error: any) {
      console.error('Failed to delete campaign:', error);
      res.status(500).json({ error: 'Failed to delete campaign' });
    }
  }
);

// ============================================
// DEFAULT SENDER ROUTES
// ============================================

/**
 * PUT /api/email-integration/default-sender
 * Set the default sender for the company.
 */
router.put(
  '/default-sender',
  requirePermission('newsletter-content-os', 'edit'),
  [body('senderId').isInt(), body('email').isEmail(), body('name').isString().notEmpty()],
  async (req: Request, res: Response) => {
    try {
      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const { senderId, email, name } = req.body;

      await emailIntegrationService.setDefaultSender(companyId, senderId, email, name);

      res.json({ success: true });
    } catch (error: any) {
      console.error('Failed to set default sender:', error);
      res.status(500).json({ error: 'Failed to set default sender' });
    }
  }
);

// ============================================
// ZOHO OAUTH ROUTES
// ============================================

/**
 * GET /api/email-integration/zoho/connect
 * Get Zoho OAuth authorization URL for the user to authorize.
 *
 * Query params:
 * - dataCenter: Zoho data center code ('com', 'eu', 'in', 'au', 'jp')
 */
router.get(
  '/zoho/connect',
  requirePermission('newsletter-content-os', 'edit'),
  async (req: Request, res: Response) => {
    try {
      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      // Get data center from query or default to 'com'
      const dataCenter = (req.query.dataCenter as string) || 'com';

      // Validate data center
      const validDataCenters = ['com', 'eu', 'in', 'au', 'jp', 'cn', 'ca'];
      if (!validDataCenters.includes(dataCenter)) {
        res.status(400).json({
          error: `Invalid data center. Must be one of: ${validDataCenters.join(', ')}`
        });
        return;
      }

      const authUrl = await emailIntegrationService.getZohoAuthorizationUrl(companyId, dataCenter);

      res.json({
        success: true,
        authUrl,
        dataCenter,
      });
    } catch (error: any) {
      console.error('Failed to generate Zoho auth URL:', error);
      res.status(500).json({ error: 'Failed to generate authorization URL' });
    }
  }
);

/**
 * POST /api/email-integration/zoho/refresh
 * Manually refresh Zoho access token.
 */
router.post(
  '/zoho/refresh',
  requirePermission('newsletter-content-os', 'edit'),
  async (req: Request, res: Response) => {
    try {
      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const result = await emailIntegrationService.refreshZohoToken(companyId);

      if (!result.success) {
        res.status(400).json({ error: result.error });
        return;
      }

      res.json({ success: true, message: 'Token refreshed successfully' });
    } catch (error: any) {
      console.error('Failed to refresh Zoho token:', error);
      res.status(500).json({ error: 'Failed to refresh token' });
    }
  }
);

/**
 * GET /api/email-integration/zoho/data-centers
 * Get available Zoho data centers for user selection.
 */
router.get('/zoho/data-centers', async (req: Request, res: Response) => {
  const dataCenters = [
    { code: 'com', name: 'United States', accountsUrl: 'accounts.zoho.com' },
    { code: 'eu', name: 'Europe', accountsUrl: 'accounts.zoho.eu' },
    { code: 'in', name: 'India', accountsUrl: 'accounts.zoho.in' },
    { code: 'au', name: 'Australia', accountsUrl: 'accounts.zoho.com.au' },
    { code: 'jp', name: 'Japan', accountsUrl: 'accounts.zoho.jp' },
    { code: 'cn', name: 'China', accountsUrl: 'accounts.zoho.com.cn' },
    { code: 'ca', name: 'Canada', accountsUrl: 'accounts.zohocloud.ca' },
  ];

  res.json({ success: true, dataCenters });
});

/**
 * GET /api/email-integration/zoho/has-platform-credentials
 * Check if platform has Zoho credentials configured.
 * Returns true if platform-level credentials are available (for multi-tenant fallback).
 */
router.get('/zoho/has-platform-credentials', async (req: Request, res: Response) => {
  try {
    const hasCredentials = emailIntegrationService.hasPlatformZohoCredentials();
    res.json({ success: true, hasPlatformCredentials: hasCredentials });
  } catch (error: any) {
    console.error('Failed to check platform credentials:', error);
    res.status(500).json({ error: 'Failed to check platform credentials' });
  }
});

/**
 * POST /api/email-integration/zoho/set-credentials
 * Set company-level Zoho OAuth credentials.
 * This allows each company/admin to use their own Zoho OAuth app.
 */
router.post(
  '/zoho/set-credentials',
  requirePermission('newsletter-content-os', 'edit'),
  [
    body('clientId').isString().notEmpty().withMessage('Client ID is required'),
    body('clientSecret').isString().notEmpty().withMessage('Client Secret is required'),
  ],
  async (req: Request, res: Response) => {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        res.status(400).json({ errors: errors.array() });
        return;
      }

      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const { clientId, clientSecret } = req.body;

      const result = await emailIntegrationService.setZohoCredentials(companyId, clientId, clientSecret);

      if (!result.success) {
        res.status(400).json({ error: result.error });
        return;
      }

      res.json({
        success: true,
        message: 'Zoho credentials saved successfully. You can now connect your Zoho Campaigns account.',
      });
    } catch (error: any) {
      console.error('Failed to set Zoho credentials:', error);
      res.status(500).json({ error: 'Failed to save Zoho credentials' });
    }
  }
);

// ============================================
// AUTOMATION WORKFLOW ROUTES
// ============================================

/**
 * GET /api/email-integration/automations
 * Get all automation workflows from email provider.
 * Query params:
 * - provider: Optional. Specify which provider to use (brevo, zoho, etc.)
 */
router.get('/automations', async (req: Request, res: Response) => {
  try {
    const companyId = req.user!.companyIds[0];
    if (!companyId) {
      res.status(400).json({ error: 'No company associated with user' });
      return;
    }

    const provider = req.query.provider as string | undefined;

    const automations = await emailIntegrationService.getAutomations(companyId, provider);

    res.json({
      success: true,
      automations,
      provider: provider || 'brevo',
    });
  } catch (error: any) {
    console.error('Failed to get automations:', error);
    res.status(500).json({ error: 'Failed to get automations', details: error.message });
  }
});

/**
 * POST /api/email-integration/automations/:workflowId/contacts
 * Add a contact to an automation workflow.
 * Body:
 * - email: string (required)
 * - attributes: Record<string, any> (optional)
 * - listIds: number[] (optional)
 * - provider: string (optional)
 */
router.post(
  '/automations/:workflowId/contacts',
  requirePermission('newsletter-content-os', 'edit'),
  [
    body('email').isEmail().withMessage('Valid email is required'),
    body('attributes').optional().isObject(),
    body('listIds').optional().isArray(),
    body('provider').optional().isString(),
  ],
  async (req: Request, res: Response) => {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        res.status(400).json({ errors: errors.array() });
        return;
      }

      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const { workflowId } = req.params;
      const { email, attributes, listIds, provider } = req.body;

      const result = await emailIntegrationService.addContactToAutomation(
        companyId,
        parseInt(workflowId, 10),
        email,
        attributes,
        listIds,
        provider
      );

      if (!result.success) {
        res.status(400).json({ error: result.message || 'Failed to add contact to automation' });
        return;
      }

      res.json({
        success: true,
        message: result.message || 'Contact added to automation successfully',
      });
    } catch (error: any) {
      console.error('Failed to add contact to automation:', error);
      res.status(500).json({ error: 'Failed to add contact to automation', details: error.message });
    }
  }
);

/**
 * DELETE /api/email-integration/automations/:workflowId/contacts/:email
 * Remove a contact from an automation workflow.
 */
router.delete(
  '/automations/:workflowId/contacts/:email',
  requirePermission('newsletter-content-os', 'edit'),
  async (req: Request, res: Response) => {
    try {
      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const { workflowId, email } = req.params;
      const { provider } = req.query;

      await emailIntegrationService.removeContactFromAutomation(
        companyId,
        parseInt(workflowId, 10),
        decodeURIComponent(email),
        provider as string
      );

      res.json({ success: true, message: 'Contact removed from automation' });
    } catch (error: any) {
      console.error('Failed to remove contact from automation:', error);
      res.status(500).json({ error: 'Failed to remove contact from automation', details: error.message });
    }
  }
);

/**
 * GET /api/email-integration/automations/:workflowId/contacts
 * Get contacts in an automation workflow.
 */
router.get('/automations/:workflowId/contacts', async (req: Request, res: Response) => {
  try {
    const companyId = req.user!.companyIds[0];
    if (!companyId) {
      res.status(400).json({ error: 'No company associated with user' });
      return;
    }

    const { workflowId } = req.params;
    const limit = parseInt(req.query.limit as string || '50', 10);
    const offset = parseInt(req.query.offset as string || '0', 10);
    const provider = req.query.provider as string | undefined;

    const result = await emailIntegrationService.getAutomationContacts(
      companyId,
      parseInt(workflowId, 10),
      limit,
      offset,
      provider
    );

    res.json({
      success: true,
      ...result,
    });
  } catch (error: any) {
    console.error('Failed to get automation contacts:', error);
    res.status(500).json({ error: 'Failed to get automation contacts', details: error.message });
  }
});

// ============================================
// MAILCHIMP WEBHOOK MANAGEMENT
// ============================================

/**
 * POST /api/email-integration/mailchimp/webhooks/:listId
 * Create a webhook for a Mailchimp list/audience.
 *
 * This allows the system to receive real-time events from Mailchimp
 * (subscribe, unsubscribe, profile updates, etc.)
 */
router.post(
  '/mailchimp/webhooks/:listId',
  requirePermission('newsletter-content-os', 'edit'),
  async (req: Request, res: Response) => {
    try {
      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const { listId } = req.params;
      const { events } = req.body;

      // Get the webhook base URL from environment or use default
      const webhookBaseUrl = process.env.WEBHOOK_BASE_URL || process.env.BACKEND_URL || 'http://localhost:3101';
      const webhookUrl = `${webhookBaseUrl}/webhooks/mailchimp`;

      // Default events if not specified
      const webhookEvents = events || [
        'subscribe',
        'unsubscribe',
        'profile',
        'cleaned',
        'upemail',
        'campaign',
      ];

      console.log('[Mailchimp] Creating webhook for list:', listId);
      console.log('[Mailchimp] Webhook URL:', webhookUrl);
      console.log('[Mailchimp] Events:', webhookEvents);

      const provider = await emailIntegrationService.getProvider(companyId, 'mailchimp');
      if (!provider) {
        res.status(400).json({ error: 'Mailchimp provider not connected' });
        return;
      }

      // Create webhook using the Mailchimp provider
      const result = await (provider as any).createWebhookForList(listId, {
        url: webhookUrl,
        events: webhookEvents,
      });

      res.json({
        success: true,
        webhook: result,
      });
    } catch (error: any) {
      console.error('Failed to create Mailchimp webhook:', error);
      res.status(500).json({
        error: 'Failed to create webhook',
        details: error.message,
      });
    }
  }
);

/**
 * GET /api/email-integration/mailchimp/webhooks
 * Get all webhooks for Mailchimp lists.
 */
router.get(
  '/mailchimp/webhooks',
  requirePermission('newsletter-content-os', 'read'),
  async (req: Request, res: Response) => {
    try {
      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const provider = await emailIntegrationService.getProvider(companyId, 'mailchimp');
      if (!provider) {
        res.status(400).json({ error: 'Mailchimp provider not connected' });
        return;
      }

      const webhooks = await provider.getWebhooks();

      res.json({
        success: true,
        webhooks,
      });
    } catch (error: any) {
      console.error('Failed to get Mailchimp webhooks:', error);
      res.status(500).json({
        error: 'Failed to get webhooks',
        details: error.message,
      });
    }
  }
);

/**
 * DELETE /api/email-integration/mailchimp/webhooks/:webhookId
 * Delete a webhook from Mailchimp.
 */
router.delete(
  '/mailchimp/webhooks/:webhookId',
  requirePermission('newsletter-content-os', 'edit'),
  async (req: Request, res: Response) => {
    try {
      const companyId = req.user!.companyIds[0];
      if (!companyId) {
        res.status(400).json({ error: 'No company associated with user' });
        return;
      }

      const { webhookId } = req.params;

      const provider = await emailIntegrationService.getProvider(companyId, 'mailchimp');
      if (!provider) {
        res.status(400).json({ error: 'Mailchimp provider not connected' });
        return;
      }

      await provider.deleteWebhook(parseInt(webhookId, 10));

      res.json({
        success: true,
        message: 'Webhook deleted successfully',
      });
    } catch (error: any) {
      console.error('Failed to delete Mailchimp webhook:', error);
      res.status(500).json({
        error: 'Failed to delete webhook',
        details: error.message,
      });
    }
  }
);

export default router;