<?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';

$page = max(1, (int)($_GET['page'] ?? 1));
$limit = min(100, max(1, (int)($_GET['limit'] ?? getListDefaultLimit())));
$offset = ($page - 1) * $limit;
$sort = (string)($_GET['sort'] ?? 'title');
$dir = strtolower((string)($_GET['dir'] ?? 'asc')) === 'desc' ? 'DESC' : 'ASC';

$sortMap = [
    'title' => 's.title',
    'artist' => 's.artist',
    'album' => 's.album',
    'created_at' => 's.created_at',
    'updated_at' => 's.updated_at',
    'play_count' => 's.play_count',
];
$orderBy = $sortMap[$sort] ?? $sortMap['title'];

try {
    $pdo = getDBConnection();
    $countStmt = $pdo->query("SELECT COUNT(*) FROM songs s WHERE COALESCE(s.is_missing, 0) = 0 AND COALESCE(s.is_hidden, 0) = 0");
    $total = (int)$countStmt->fetchColumn();

    $stmt = $pdo->prepare(apiSongSelectSql() . "
        WHERE COALESCE(s.is_missing, 0) = 0 AND COALESCE(s.is_hidden, 0) = 0
        ORDER BY {$orderBy} {$dir}, s.id ASC
        LIMIT :limit OFFSET :offset
    ");
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();

    $songs = array_map('apiSongPublicPayload', $stmt->fetchAll());
    apiSuccess([
        'songs' => $songs,
    ], '', [
        'page' => $page,
        'limit' => $limit,
        'total' => $total,
        'total_pages' => (int)ceil($total / $limit),
        'sort' => $sort,
        'dir' => strtolower($dir),
    ], [
        'songs' => $songs,
    ]);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) writeAppLog('error', 'songs_api_error', 'Songs API failed', ['error' => $e->getMessage()]);
    apiError('곡 목록을 불러오지 못했습니다.', 'server_error', 500);
}
