<?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('ls.created_at AS liked_at') . "
        WHERE COALESCE(s.is_missing, 0) = 0
          AND COALESCE(s.is_hidden, 0) = 0
          AND ls.id IS NOT NULL
        ORDER BY ls.created_at DESC
        LIMIT :limit
    ");
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->execute();
    $songs = array_map(function ($song) {
        $payload = apiSongPublicPayload($song);
        $payload['liked_at'] = ensureUtf8String($song['liked_at'] ?? '');
        return $payload;
    }, $stmt->fetchAll());
    apiSuccess(['songs' => $songs], '', ['limit' => $limit], ['songs' => $songs]);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) writeAppLog('error', 'liked_api_error', 'Liked API failed', ['error' => $e->getMessage()]);
    apiError('좋아요 목록을 불러오지 못했습니다.', 'server_error', 500);
}
