import { Router, Request, Response } from 'express';
import { authMiddleware } from '../middleware/auth';
import { auditAdminAccess, requireAdminAccess } from '../middleware/admin';
import pool from '../db';
import { runEngagementCycle, processMentions } from '../twitter/services/twitter-engagement.service';
import { trackPerformance } from '../workers/social-engine/performance-tracker';

const router = Router();

router.use(authMiddleware, requireAdminAccess, auditAdminAccess('admin-social-bot'));

router.get('/summary', async (req: Request, res: Response) => {
  try {
    const [tweetCounts, engagementCounts, latestTweets, latestEngagements, latestSocial] = await Promise.all([
      pool.query(
        `SELECT
           COUNT(*) FILTER (WHERE created_at > NOW() - INTERVAL '24 hours') AS tweets_24h,
           COUNT(*) FILTER (WHERE status = 'preview' AND created_at > NOW() - INTERVAL '24 hours') AS previews_24h
         FROM rm_twitter_tweets`
      ),
      pool.query(
        `SELECT
           COUNT(*) FILTER (WHERE created_at > NOW() - INTERVAL '24 hours') AS engagement_24h,
           COUNT(*) FILTER (WHERE action_type = 'mention_reply' AND created_at > NOW() - INTERVAL '24 hours') AS mention_replies_24h,
           MAX(created_at) AS last_engagement_at
         FROM rm_twitter_engagement`
      ),
      pool.query(
        `SELECT tweet_id, content_type, status, created_at
         FROM rm_twitter_tweets
         ORDER BY created_at DESC
         LIMIT 5`
      ),
      pool.query(
        `SELECT action_type, target_tweet_id, created_at
         FROM rm_twitter_engagement
         ORDER BY created_at DESC
         LIMIT 10`
      ),
      pool.query(
        `SELECT c.tweet_id, c.content_type, c.format, c.posted_at, perf.impressions, perf.likes, perf.replies, perf.engagement_rate
         FROM rm_social_content c
         LEFT JOIN rm_social_performance perf ON perf.content_id = c.id
         WHERE c.status = 'posted' AND c.tweet_id IS NOT NULL AND c.tweet_id NOT LIKE 'dry_%'
         ORDER BY c.posted_at DESC NULLS LAST
         LIMIT 5`
      ),
    ]);

    res.json({
      ok: true,
      bot: {
        dryRun: process.env.TWITTER_DRY_RUN === 'true',
        maxTweets24h: parseInt(process.env.RAINMAKER_MAX_TWEETS_24H || '40', 10),
      },
      counts: {
        tweets24h: Number(tweetCounts.rows[0]?.tweets_24h || 0),
        previews24h: Number(tweetCounts.rows[0]?.previews_24h || 0),
        engagement24h: Number(engagementCounts.rows[0]?.engagement_24h || 0),
        mentionReplies24h: Number(engagementCounts.rows[0]?.mention_replies_24h || 0),
      },
      lastEngagementAt: engagementCounts.rows[0]?.last_engagement_at || null,
      latestTweets: latestTweets.rows,
      latestEngagements: latestEngagements.rows,
      latestSocialPosts: latestSocial.rows,
    });
  } catch (err: any) {
    console.error('[admin-social-bot] Summary error:', err.message);
    res.status(500).json({ error: 'Failed to fetch social bot summary' });
  }
});

router.post('/run/engagement', async (req: Request, res: Response) => {
  try {
    const actions = await runEngagementCycle();
    res.json({ ok: true, actions });
  } catch (err: any) {
    console.error('[admin-social-bot] Engagement run error:', err.message);
    res.status(500).json({ error: 'Failed to run engagement cycle' });
  }
});

router.post('/run/mentions', async (req: Request, res: Response) => {
  try {
    const replies = await processMentions();
    res.json({ ok: true, replies });
  } catch (err: any) {
    console.error('[admin-social-bot] Mention run error:', err.message);
    res.status(500).json({ error: 'Failed to process mentions' });
  }
});

router.post('/run/performance', async (req: Request, res: Response) => {
  try {
    await trackPerformance();
    res.json({ ok: true });
  } catch (err: any) {
    console.error('[admin-social-bot] Performance run error:', err.message);
    res.status(500).json({ error: 'Failed to run performance tracker' });
  }
});

export default router;
