<?php
/**
 * API - Ver estado de la cola de media (media_queue)
 * GET /api/media_queue_status.php - Lista la cola
 * GET /api/media_queue_status.php?action=retry&id=123 - Reintenta un item
 * GET /api/media_queue_status.php?action=stats - Resumen rápido
 */
require_once __DIR__ . '/../config/config.php';

error_reporting(E_ALL);
ini_set('display_errors', 0);

requireAuthentication();

header('Content-Type: application/json; charset=utf-8');

$db = Database::getInstance();
$action = $_GET['action'] ?? 'list';

try {
    switch ($action) {
        case 'stats':
            $stats = $db->fetchAll("SELECT status, COUNT(*) as total FROM media_queue GROUP BY status");
            $result = ['pending' => 0, 'processing' => 0, 'done' => 0, 'failed' => 0, 'permanently_failed' => 0];
            foreach ($stats as $s) {
                $result[$s['status']] = intval($s['total']);
            }
            $result['total'] = array_sum($result);
            
            // Últimos 5 errores
            $lastErrors = $db->fetchAll("SELECT id, media_id, media_url, status, attempts, result, created_at FROM media_queue WHERE status IN ('failed','permanently_failed') ORDER BY created_at DESC LIMIT 5");
            
            echo json_encode(['success' => true, 'stats' => $result, 'last_errors' => $lastErrors], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            break;

        case 'retry':
            $id = intval($_GET['id'] ?? 0);
            if (!$id) {
                echo json_encode(['success' => false, 'error' => 'Se requiere id']);
                exit;
            }
            $db->query("UPDATE media_queue SET status = 'pending', attempts = 0, result = NULL WHERE id = :id", ['id' => $id]);
            echo json_encode(['success' => true, 'message' => "Item #{$id} marcado para reintento"]);
            break;

        case 'retry_all':
            $db->query("UPDATE media_queue SET status = 'pending', attempts = 0, result = NULL WHERE status IN ('failed', 'permanently_failed')");
            $affected = $db->fetch("SELECT ROW_COUNT() as cnt");
            echo json_encode(['success' => true, 'message' => "Todos los fallidos marcados para reintento"]);
            break;

        case 'list':
        default:
            $status = $_GET['status'] ?? null;
            $limit = min(intval($_GET['limit'] ?? 50), 200);
            
            $where = '';
            $params = [];
            if ($status) {
                $where = ' WHERE status = :status';
                $params['status'] = $status;
            }
            
            $rows = $db->fetchAll(
                "SELECT mq.*, c.message_type, c.filename as conv_filename, c.content as conv_content
                 FROM media_queue mq 
                 LEFT JOIN conversations c ON c.id = mq.conversation_id
                 {$where} 
                 ORDER BY mq.created_at DESC 
                 LIMIT {$limit}",
                $params
            );
            
            // Stats rápidas
            $statsRaw = $db->fetchAll("SELECT status, COUNT(*) as total FROM media_queue GROUP BY status");
            $stats = [];
            foreach ($statsRaw as $s) $stats[$s['status']] = intval($s['total']);
            
            echo json_encode([
                'success' => true,
                'stats' => $stats,
                'count' => count($rows),
                'items' => $rows
            ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            break;
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
