<?php
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/auth.php';
require_once dirname(__DIR__) . '/includes/api.php';
require_once dirname(__DIR__) . '/includes/functions_notes.php';

apiRequireMethod('POST');
apiRequireCsrf();

try {
    $songId = (int)($_POST['song_id'] ?? 0);
    $action = (string)($_POST['action'] ?? 'save');
    if ($songId <= 0) {
        apiError('곡 정보를 확인할 수 없습니다.', 'INVALID_REQUEST', 400);
    }

    if ($action === 'delete') {
        deleteSongNote($songId);
        $note = '';
        $message = '메모를 삭제했습니다.';
    } else {
        saveSongNote($songId, $_POST['note_text'] ?? '');
        $row = getSongNote($songId);
        $note = $row ? (string)$row['note_text'] : '';
        $message = '메모를 저장했습니다.';
    }

    apiSuccess(
        ['note' => $note],
        $message,
        [],
        ['note' => $note]
    );
} catch (Throwable $e) {
    apiHandleThrowable($e, 'SERVER_ERROR', 500, [
        'song_id' => $_POST['song_id'] ?? null,
        'action' => $_POST['action'] ?? null,
    ]);
}
