// backend/src/routes/admin.js
import { Router } from 'express';
import { requireAuth, requireSuperAdmin } from '../middleware/auth.js';
import { query } from '../utils/db.js';
import { logger } from '../utils/logger.js';

const router = Router();
router.use(requireAuth, requireSuperAdmin);

// GET /api/admin/dashboard  — platform overview
router.get('/dashboard', async (req, res) => {
  const [users, revenue, runs, content] = await Promise.all([
    query(`SELECT
      COUNT(*) as total,
      COUNT(*) FILTER (WHERE status = 'active') as active,
      COUNT(*) FILTER (WHERE status = 'trial') as trial,
      COUNT(*) FILTER (WHERE status = 'past_due') as past_due,
      COUNT(*) FILTER (WHERE status = 'canceled') as canceled,
      COUNT(*) FILTER (WHERE status = 'banned') as banned,
      COUNT(*) FILTER (WHERE created_at > NOW() - INTERVAL '30 days') as new_last_30d,
      COUNT(*) FILTER (WHERE plan_id = 'starter' AND status = 'active') as starter_active,
      COUNT(*) FILTER (WHERE plan_id = 'pro' AND status = 'active') as pro_active,
      COUNT(*) FILTER (WHERE plan_id = 'agency' AND status = 'active') as agency_active
      FROM users WHERE role = 'client'`),
    query(`SELECT
      COALESCE(SUM(CASE WHEN u.plan_id = 'starter' THEN 29 WHEN u.plan_id = 'pro' THEN 79 WHEN u.plan_id = 'agency' THEN 199 END), 0) as mrr
      FROM users u WHERE u.status = 'active' AND u.role = 'client'`),
    query(`SELECT
      COUNT(*) as total_runs,
      COUNT(*) FILTER (WHERE status = 'completed') as completed,
      COUNT(*) FILTER (WHERE status = 'failed') as failed,
      COUNT(*) FILTER (WHERE created_at > NOW() - INTERVAL '24 hours') as last_24h
      FROM pipeline_runs`),
    query(`SELECT COUNT(*) as total FROM generated_content`),
  ]);

  res.json({
    users: users.rows[0],
    revenue: revenue.rows[0],
    runs: runs.rows[0],
    content: content.rows[0],
  });
});

// GET /api/admin/users  — paginated user list
router.get('/users', async (req, res) => {
  const { page = 1, limit = 25, search, status, plan } = req.query;
  const offset = (parseInt(page) - 1) * parseInt(limit);

  let where = "WHERE u.role = 'client'";
  const params = [];
  let idx = 1;

  if (search) { where += ` AND (u.email ILIKE $${idx} OR u.full_name ILIKE $${idx})`; params.push(`%${search}%`); idx++; }
  if (status) { where += ` AND u.status = $${idx++}`; params.push(status); }
  if (plan) { where += ` AND u.plan_id = $${idx++}`; params.push(plan); }

  const { rows } = await query(
    `SELECT u.id, u.email, u.full_name, u.status, u.plan_id, u.locale,
            u.trial_ends_at, u.current_period_end, u.created_at, u.email_verified,
            u.stripe_customer_id, u.stripe_subscription_status,
            COUNT(pr.id) as total_runs,
            COUNT(gc.id) as total_content
     FROM users u
     LEFT JOIN pipeline_runs pr ON pr.user_id = u.id
     LEFT JOIN generated_content gc ON gc.user_id = u.id
     ${where}
     GROUP BY u.id
     ORDER BY u.created_at DESC
     LIMIT $${idx++} OFFSET $${idx}`,
    [...params, parseInt(limit), offset]
  );

  const { rows: countRows } = await query(`SELECT COUNT(*) FROM users u ${where}`, params);

  res.json({ users: rows, total: parseInt(countRows[0].count), page: parseInt(page) });
});

// GET /api/admin/users/:id  — single user detail
router.get('/users/:id', async (req, res) => {
  const { rows } = await query(
    `SELECT u.*, p.name as plan_name, p.price_usd,
            up.niche, up.brand_name, up.target_audience
     FROM users u
     LEFT JOIN plans p ON u.plan_id = p.id
     LEFT JOIN user_profiles up ON up.user_id = u.id
     WHERE u.id = $1`,
    [req.params.id]
  );
  if (!rows[0]) return res.status(404).json({ error: 'User not found' });

  const { rows: runs } = await query(
    'SELECT id, status, triggered_by, scripts_count, started_at, completed_at FROM pipeline_runs WHERE user_id = $1 ORDER BY created_at DESC LIMIT 10',
    [req.params.id]
  );

  res.json({ ...rows[0], recentRuns: runs });
});

// PATCH /api/admin/users/:id/status  — ban/activate/etc
router.patch('/users/:id/status', async (req, res) => {
  const { status } = req.body;
  const validStatuses = ['active', 'trial', 'past_due', 'canceled', 'banned'];
  if (!validStatuses.includes(status)) return res.status(400).json({ error: 'Invalid status' });

  await query('UPDATE users SET status = $1, updated_at = NOW() WHERE id = $2', [status, req.params.id]);

  await query(
    `INSERT INTO audit_logs (actor_id, target_user_id, action, details) VALUES ($1, $2, $3, $4)`,
    [req.user.id, req.params.id, 'status_change', JSON.stringify({ newStatus: status })]
  );

  logger.info(`Admin ${req.user.email} changed user ${req.params.id} status to ${status}`);
  res.json({ success: true });
});

// PATCH /api/admin/users/:id/plan  — change plan
router.patch('/users/:id/plan', async (req, res) => {
  const { planId } = req.body;
  if (!['starter', 'pro', 'agency'].includes(planId)) return res.status(400).json({ error: 'Invalid plan' });

  await query('UPDATE users SET plan_id = $1, updated_at = NOW() WHERE id = $2', [planId, req.params.id]);
  await query('INSERT INTO audit_logs (actor_id, target_user_id, action, details) VALUES ($1, $2, $3, $4)',
    [req.user.id, req.params.id, 'plan_change', JSON.stringify({ newPlan: planId })]);

  res.json({ success: true });
});

// DELETE /api/admin/users/:id  — delete user + all data
router.delete('/users/:id', async (req, res) => {
  if (req.params.id === req.user.id) return res.status(400).json({ error: 'Cannot delete yourself' });
  await query('DELETE FROM users WHERE id = $1', [req.params.id]);
  await query('INSERT INTO audit_logs (actor_id, action, details) VALUES ($1, $2, $3)',
    [req.user.id, 'user_deleted', JSON.stringify({ deletedUserId: req.params.id })]);
  res.json({ success: true });
});

// GET /api/admin/audit  — audit log
router.get('/audit', async (req, res) => {
  const { rows } = await query(
    `SELECT al.*, u.email as actor_email, tu.email as target_email
     FROM audit_logs al
     LEFT JOIN users u ON al.actor_id = u.id
     LEFT JOIN users tu ON al.target_user_id = tu.id
     ORDER BY al.created_at DESC LIMIT 100`
  );
  res.json(rows);
});

// GET /api/admin/plans  — manage plans
router.get('/plans', async (req, res) => {
  const { rows } = await query('SELECT * FROM plans ORDER BY price_usd ASC');
  res.json(rows);
});

// PATCH /api/admin/plans/:id  — update plan stripe price id
router.patch('/plans/:id', async (req, res) => {
  const { stripePriceId, active } = req.body;
  await query(
    'UPDATE plans SET stripe_price_id = COALESCE($1, stripe_price_id), active = COALESCE($2, active) WHERE id = $3',
    [stripePriceId, active, req.params.id]
  );
  res.json({ success: true });
});

export default router;
