import { Router, Request, Response, NextFunction } from 'express';
import { query, queryOne } from '../db';
import { logger } from '../logger';
import { strictActionLimiter } from '../middleware/rateLimit';
import { runEnrichmentJob } from '../services/enrichmentService';
import { sendApprovedEnrichedEmails } from '../services/enrichedSendService';

const router = Router();

/** GET /api/campaigns/:id/settings */
router.get('/:id/settings', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const row = await queryOne(
      `SELECT * FROM campaign_settings WHERE campaign_id = $1`,
      [req.params.id]
    );
    if (!row) {
      return res.json({
        campaign_id: req.params.id,
        enrichment_enabled: false,
        enrichment_tone: null,
        enrichment_instructions: null,
        send_from_email: null,
        send_from_name: null,
        reply_unsubscribe_enabled: false,
        unsubscribe_response_template: null,
        enrich_unsubscribe_response: false,
        auto_forward_emails: [],
        auto_bcc_emails: [],
      });
    }
    res.json(row);
  } catch (err) {
    next(err);
  }
});

/** PUT /api/campaigns/:id/settings */
router.put('/:id/settings', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const {
      enrichment_enabled,
      enrichment_tone,
      enrichment_instructions,
      send_from_email,
      send_from_name,
      reply_unsubscribe_enabled,
      unsubscribe_response_template,
      enrich_unsubscribe_response,
      auto_forward_emails,
      auto_bcc_emails,
    } = req.body;

    const row = await queryOne(
      `INSERT INTO campaign_settings (
        campaign_id, enrichment_enabled, enrichment_tone, enrichment_instructions,
        send_from_email, send_from_name, reply_unsubscribe_enabled,
        unsubscribe_response_template, enrich_unsubscribe_response,
        auto_forward_emails, auto_bcc_emails
      ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)
      ON CONFLICT (campaign_id) DO UPDATE SET
        enrichment_enabled = EXCLUDED.enrichment_enabled,
        enrichment_tone = EXCLUDED.enrichment_tone,
        enrichment_instructions = EXCLUDED.enrichment_instructions,
        send_from_email = EXCLUDED.send_from_email,
        send_from_name = EXCLUDED.send_from_name,
        reply_unsubscribe_enabled = EXCLUDED.reply_unsubscribe_enabled,
        unsubscribe_response_template = EXCLUDED.unsubscribe_response_template,
        enrich_unsubscribe_response = EXCLUDED.enrich_unsubscribe_response,
        auto_forward_emails = EXCLUDED.auto_forward_emails,
        auto_bcc_emails = EXCLUDED.auto_bcc_emails,
        updated_at = now()
      RETURNING *`,
      [
        req.params.id,
        !!enrichment_enabled,
        enrichment_tone ?? null,
        enrichment_instructions ?? null,
        send_from_email ?? null,
        send_from_name ?? null,
        !!reply_unsubscribe_enabled,
        unsubscribe_response_template ?? null,
        !!enrich_unsubscribe_response,
        Array.isArray(auto_forward_emails) ? auto_forward_emails : [],
        Array.isArray(auto_bcc_emails) ? auto_bcc_emails : [],
      ]
    );
    res.json(row);
  } catch (err) {
    next(err);
  }
});

/** POST /api/campaigns/:id/enrich */
router.post('/:id/enrich', strictActionLimiter, async (req: Request, res: Response, next: NextFunction) => {
  try {
    runEnrichmentJob(req.params.id).catch(e => logger.error(e, '[enrich job]'));
    res.json({ message: 'Enrichment job started' });
  } catch (err) {
    next(err);
  }
});

/** GET /api/campaigns/:id/enriched?status=pending_review */
router.get('/:id/enriched', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const status = req.query.status as string | undefined;
    const params: unknown[] = [req.params.id];
    let sql = `
      SELECT e.*, c.email, c.first_name, c.last_name
      FROM campaign_enriched_emails e
      JOIN contacts c ON c.id = e.contact_id
      WHERE e.campaign_id = $1`;
    if (status) {
      sql += ` AND e.status = $2`;
      params.push(status);
    }
    sql += ` ORDER BY c.email ASC`;
    const rows = await query(sql, params);
    res.json(rows);
  } catch (err) {
    next(err);
  }
});

/** PUT /api/campaigns/:id/enriched/approve-all */
router.put('/:id/enriched/approve-all', async (req: Request, res: Response, next: NextFunction) => {
  try {
    await query(
      `UPDATE campaign_enriched_emails SET status = 'approved', reviewed_at = now(), updated_at = now()
       WHERE campaign_id = $1 AND status = 'pending_review'`,
      [req.params.id]
    );
    res.json({ message: 'All pending approved' });
  } catch (err) {
    next(err);
  }
});

/** PUT /api/campaigns/:id/enriched/reject-all */
router.put('/:id/enriched/reject-all', async (req: Request, res: Response, next: NextFunction) => {
  try {
    await query(
      `UPDATE campaign_enriched_emails SET status = 'rejected', reviewed_at = now(), updated_at = now()
       WHERE campaign_id = $1 AND status = 'pending_review'`,
      [req.params.id]
    );
    res.json({ message: 'All pending rejected' });
  } catch (err) {
    next(err);
  }
});

/** PUT /api/campaigns/:id/enriched/:emailId/approve */
router.put('/:id/enriched/:emailId/approve', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const row = await queryOne(
      `UPDATE campaign_enriched_emails SET status = 'approved', reviewed_at = now(), updated_at = now()
       WHERE id = $1 AND campaign_id = $2 RETURNING *`,
      [req.params.emailId, req.params.id]
    );
    if (!row) return res.status(404).json({ error: 'Enriched row not found' });
    res.json(row);
  } catch (err) {
    next(err);
  }
});

/** PUT /api/campaigns/:id/enriched/:emailId/reject */
router.put('/:id/enriched/:emailId/reject', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const row = await queryOne(
      `UPDATE campaign_enriched_emails SET status = 'rejected', reviewed_at = now(), updated_at = now()
       WHERE id = $1 AND campaign_id = $2 RETURNING *`,
      [req.params.emailId, req.params.id]
    );
    if (!row) return res.status(404).json({ error: 'Enriched row not found' });
    res.json(row);
  } catch (err) {
    next(err);
  }
});

/** POST /api/campaigns/:id/send-enriched */
router.post('/:id/send-enriched', strictActionLimiter, async (req: Request, res: Response, next: NextFunction) => {
  try {
    sendApprovedEnrichedEmails(req.params.id).catch(e => logger.error(e, '[send-enriched]'));
    res.json({ message: 'Send enriched campaign initiated' });
  } catch (err) {
    next(err);
  }
});

/** GET /api/campaigns/:id/inbox */
router.get('/:id/inbox', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const rows = await query(
      `SELECT * FROM inbox_messages WHERE campaign_id = $1 ORDER BY created_at DESC LIMIT 200`,
      [req.params.id]
    );
    res.json(rows);
  } catch (err) {
    next(err);
  }
});

export default router;
