<?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('ph.last_played_at AS last_played_at') . "
        INNER JOIN (
            SELECT song_id, MAX(played_at) AS last_played_at
            FROM play_history
            WHERE played_at >= DATE_SUB(NOW(), INTERVAL 365 DAY)
            GROUP BY song_id
        ) ph ON ph.song_id = s.id
        WHERE COALESCE(s.is_missing, 0) = 0 AND COALESCE(s.is_hidden, 0) = 0
        ORDER BY last_played_at DESC
        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', 'recent_api_error', 'Recent API failed', ['error' => $e->getMessage()]);
    apiError('최근 재생 목록을 불러오지 못했습니다.', 'server_error', 500);
}
