<?php
require_once '../../config/cors.php';
require_once '../../config/db.php';
require_once '../../helpers/response.php';
require_once '../../helpers/auth.php';

$admin = requireAdmin();
$stream_id = $_GET['stream_id'] ?? null;

if (!$stream_id) {
    sendError('Stream ID required', 400);
}

$stmt = $pdo->prepare("
    SELECT 
        cm.id, 
        cm.message, 
        cm.created_at,
        cm.user_type,
        cm.is_deleted,
        CASE 
            WHEN cm.user_type = 'public' THEN pu.display_name
            WHEN cm.user_type = 'admin' THEN u.name
            ELSE 'Unknown'
        END as user_name,
        pu.email as user_email
    FROM chat_messages cm
    LEFT JOIN public_users pu ON pu.id = cm.user_id AND cm.user_type = 'public'
    LEFT JOIN users u ON u.id = cm.admin_id AND cm.user_type = 'admin'
    WHERE cm.stream_id = ?
    ORDER BY cm.created_at DESC
    LIMIT 200
");
$stmt->execute([$stream_id]);
$messages = $stmt->fetchAll();

sendSuccess($messages);
?>