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

$playlistId = isset($_GET['id']) ? (int)$_GET['id'] : (isset($_GET['playlist_id']) ? (int)$_GET['playlist_id'] : 0);
if ($playlistId <= 0) {
    apiError('올바르지 않은 플레이리스트 ID입니다.', 'invalid_playlist_id', 400);
}

try {
    $pdo = getDBConnection();
    $playlistStmt = $pdo->prepare("
        SELECT id, name, description, display_scope, created_at, updated_at
        FROM playlists
        WHERE id = :id
        LIMIT 1
    ");
    $playlistStmt->execute([':id' => $playlistId]);
    $playlist = $playlistStmt->fetch();
    if (!$playlist) {
        apiError('플레이리스트를 찾을 수 없습니다.', 'playlist_not_found', 404);
    }

    $songStmt = $pdo->prepare(apiSongSelectSql('ps.sort_order, ps.created_at AS added_at') . "
        INNER JOIN playlist_songs ps ON ps.song_id = s.id
        WHERE ps.playlist_id = :playlist_id
          AND COALESCE(s.is_missing, 0) = 0
          AND COALESCE(s.is_hidden, 0) = 0
        ORDER BY ps.sort_order ASC, ps.id ASC
    ");
    $songStmt->execute([':playlist_id' => $playlistId]);
    $songs = array_map(function ($song) {
        $payload = apiSongPublicPayload($song);
        $payload['sort_order'] = (int)($song['sort_order'] ?? 0);
        $payload['added_at'] = ensureUtf8String($song['added_at'] ?? '');
        return $payload;
    }, $songStmt->fetchAll());

    $data = [
        'playlist' => [
            'id' => (int)$playlist['id'],
            'name' => ensureUtf8String($playlist['name'] ?? ''),
            'description' => ensureUtf8String($playlist['description'] ?? ''),
            'display_scope' => normalizePlaylistDisplayScope18($playlist['display_scope'] ?? 'private'),
            'display_scope_label' => playlistDisplayScopeLabel18($playlist['display_scope'] ?? 'private'),
            'created_at' => ensureUtf8String($playlist['created_at'] ?? ''),
            'updated_at' => ensureUtf8String($playlist['updated_at'] ?? ''),
            'song_count' => count($songs),
            'total_duration' => array_sum(array_map(function ($song) {
                return (int)($song['duration'] ?? 0);
            }, $songs)),
            'cover_ids' => array_slice(array_map(function ($song) {
                return (int)($song['id'] ?? 0);
            }, $songs), 0, 4),
        ],
        'songs' => $songs,
    ];
    apiSuccess($data, '', ['song_count' => count($songs)], $data);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) writeAppLog('error', 'playlist_api_error', 'Playlist API failed', ['playlist_id' => $playlistId, 'error' => $e->getMessage()]);
    apiError('플레이리스트를 불러오지 못했습니다.', 'server_error', 500);
}
