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

require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';
require_once dirname(__DIR__) . '/includes/api.php';

$limit = min(100, max(1, (int)($_GET['limit'] ?? getListDefaultLimit())));

try {
    $pdo = getDBConnection();
    $stmt = $pdo->prepare(apiSongSelectSql() . "
        WHERE COALESCE(s.is_missing, 0) = 0 AND COALESCE(s.is_hidden, 0) = 0
        ORDER BY s.play_count DESC, s.title ASC
        LIMIT :limit
    ");
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->execute();
    $songs = array_map('apiSongPublicPayload', $stmt->fetchAll());
    apiSuccess(['songs' => $songs], '', ['limit' => $limit], ['songs' => $songs]);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) writeAppLog('error', 'popular_api_error', 'Popular API failed', ['error' => $e->getMessage()]);
    apiError('많이 들은 곡을 불러오지 못했습니다.', 'server_error', 500);
}
