<?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);
    $rating = (int)($_POST['rating'] ?? 0);
    if ($songId <= 0) {
        apiError('곡 정보를 확인할 수 없습니다.', 'INVALID_REQUEST', 400);
    }
    if ($rating < 0 || $rating > 5) {
        apiError('별점은 0점부터 5점까지만 저장할 수 있습니다.', 'VALIDATION_ERROR', 400);
    }

    saveSongRating($songId, $rating);
    apiSuccess(
        ['rating' => $rating],
        '별점을 저장했습니다.',
        [],
        ['rating' => $rating]
    );
} catch (Throwable $e) {
    apiHandleThrowable($e, 'SERVER_ERROR', 500, [
        'song_id' => $_POST['song_id'] ?? null,
    ]);
}
