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

ini_set('display_errors', 0);
error_reporting(E_ALL);

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

try {
    $pdo = getDBConnection();
    $stmt = $pdo->query("
        SELECT p.id, p.name, p.description, p.display_scope, COUNT(ps.id) AS song_count, COALESCE(SUM(s.duration), 0) AS total_duration
        FROM playlists p
        LEFT JOIN playlist_songs ps ON p.id = ps.playlist_id
        LEFT JOIN songs s ON s.id = ps.song_id AND COALESCE(s.is_missing, 0) = 0 AND COALESCE(s.is_hidden, 0) = 0
        WHERE COALESCE(p.display_scope, 'private') != 'hidden'
        GROUP BY p.id, p.name, p.description, p.display_scope
        ORDER BY (p.display_scope = 'home') DESC, p.name ASC
    ");
    $playlists = array_map(function ($playlist) {
        return [
            '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'),
            'song_count' => (int)($playlist['song_count'] ?? 0),
            'total_duration' => (int)($playlist['total_duration'] ?? 0),
        ];
    }, $stmt->fetchAll());

    apiSuccess(['playlists' => $playlists], '', ['count' => count($playlists)], ['playlists' => $playlists]);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'playlist_error', 'Playlist list load failed', ['error' => $e->getMessage()]);
    }
    apiError('플레이리스트 목록을 불러오지 못했습니다.', 'server_error', 500);
}
