<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/auth.php';
require_once dirname(__DIR__) . '/includes/functions.php';
require_once dirname(__DIR__) . '/includes/api.php';

apiRequireMethod('POST');
apiRequireCsrf();

$playlistId = isset($_POST['playlist_id']) ? (int)$_POST['playlist_id'] : 0;
$orderRaw = $_POST['order'] ?? '[]';
$order = is_string($orderRaw) ? json_decode($orderRaw, true) : $orderRaw;

if ($playlistId <= 0 || !is_array($order)) {
    apiError('저장할 순서 정보가 올바르지 않습니다.', 'VALIDATION_ERROR', 400);
}

$ids = [];
foreach ($order as $value) {
    $id = (int)$value;
    if ($id > 0) {
        $ids[] = $id;
    }
}
$ids = array_values(array_unique($ids));

if (empty($ids)) {
    apiError('저장할 곡이 없습니다.', 'VALIDATION_ERROR', 400);
}

try {
    $pdo = getDBConnection();
    $pdo->beginTransaction();

    $playlistCheck = $pdo->prepare("SELECT id FROM playlists WHERE id = :id");
    $playlistCheck->execute([':id' => $playlistId]);
    if (!$playlistCheck->fetch()) {
        $pdo->rollBack();
        apiError('플레이리스트를 찾을 수 없습니다.', 'NOT_FOUND', 404);
    }

    $update = $pdo->prepare("
        UPDATE playlist_songs
        SET sort_order = :sort_order
        WHERE id = :id AND playlist_id = :playlist_id
    ");

    foreach ($ids as $index => $playlistSongId) {
        $update->execute([
            ':sort_order' => $index + 1,
            ':id' => $playlistSongId,
            ':playlist_id' => $playlistId,
        ]);
    }

    $touch = $pdo->prepare("UPDATE playlists SET updated_at = NOW() WHERE id = :id");
    $touch->execute([':id' => $playlistId]);
    $pdo->commit();

    apiSuccess(
        ['playlist_id' => $playlistId, 'count' => count($ids)],
        '플레이리스트 순서를 저장했습니다.'
    );
} catch (Throwable $e) {
    if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    apiHandleThrowable($e, 'SERVER_ERROR', 500, [
        'playlist_id' => $playlistId,
    ]);
}
