import { Router, Request, Response } from 'express';
import { requireEditor } from '../middleware/staffbaseAuth';
import { syncMatches, evaluateTips } from '../services/syncService';
import { query } from '../db/client';
import { checkDbConnection } from '../db/client';
import { logger } from '../services/logger';

const router = Router();

// Alle Admin-Routen erfordern Editor-Rolle
router.use(requireEditor);

/**
 * POST /api/admin/sync
 * Manueller Trigger: Spiele von football-data.org synchronisieren
 */
router.post('/sync', async (_req: Request, res: Response): Promise<void> => {
  try {
    logger.info('Manual sync triggered');
    const result = await syncMatches();
    res.json({ success: true, ...result });
  } catch (error: unknown) {
    const msg = error instanceof Error ? error.message : String(error);
    logger.error('Manual sync failed', { message: msg });
    res.status(500).json({
      success: false,
      error: msg,
    });
  }
});

/**
 * POST /api/admin/evaluate
 * Manueller Trigger: Tipps für abgeschlossene Spiele auswerten
 */
router.post('/evaluate', async (_req: Request, res: Response): Promise<void> => {
  try {
    logger.info('Manual tip evaluation triggered');
    const result = await evaluateTips();
    res.json({ success: true, ...result });
  } catch (error) {
    logger.error('Manual evaluation failed', { error });
    res.status(500).json({
      success: false,
      error: (error as Error).message,
    });
  }
});

/**
 * POST /api/admin/refresh-leaderboard
 * Materialized View manuell aktualisieren
 */
router.post('/refresh-leaderboard', async (_req: Request, res: Response): Promise<void> => {
  try {
    await query('REFRESH MATERIALIZED VIEW CONCURRENTLY leaderboard');
    logger.info('Leaderboard refreshed manually');
    res.json({ success: true, message: 'Leaderboard refreshed' });
  } catch (error) {
    logger.error('Failed to refresh leaderboard', { error });
    res.status(500).json({ success: false, error: (error as Error).message });
  }
});

/**
 * GET /api/admin/stats
 * Allgemeine Statistiken (für Admin-Dashboard)
 */
router.get('/stats', async (_req: Request, res: Response): Promise<void> => {
  try {
    const [matchStats, tipStats, syncStats] = await Promise.all([
      query<{ total: string; finished: string; scheduled: string }>(
        `SELECT
           COUNT(*) AS total,
           COUNT(*) FILTER (WHERE status = 'FINISHED') AS finished,
           COUNT(*) FILTER (WHERE status IN ('SCHEDULED','TIMED')) AS scheduled
         FROM matches`
      ),
      query<{ total: string; evaluated: string; pending: string }>(
        `SELECT
           COUNT(*) AS total,
           COUNT(*) FILTER (WHERE points IS NOT NULL) AS evaluated,
           COUNT(*) FILTER (WHERE points IS NULL) AS pending
         FROM tips`
      ),
      query<{ synced_at: Date; status: string; matches_new: number }>(
        'SELECT synced_at, status, matches_new FROM sync_log ORDER BY synced_at DESC LIMIT 1'
      ),
    ]);

    res.json({
      matches: matchStats[0],
      tips: tipStats[0],
      lastSync: syncStats[0] ?? null,
    });
  } catch (error) {
    logger.error('Failed to fetch admin stats', { error });
    res.status(500).json({ error: 'Internal server error' });
  }
});

export default router;
