<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/playback_failures.php';

function playbackFailureJson($success, $message, $data = [], $statusCode = 200) {
    http_response_code($statusCode);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(array_merge([
        'success' => (bool)$success,
        'message' => ensureUtf8String($message),
    ], $data), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
    exit;
}

if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'POST') {
    playbackFailureJson(false, '지원하지 않는 요청입니다.', [], 405);
}

requireCsrfToken();

try {
    $songId = isset($_POST['song_id']) ? (int)$_POST['song_id'] : 0;
    $errorType = normalizePlaybackFailureType($_POST['error_type'] ?? 'client_error');
    if ($errorType === 'unknown') $errorType = 'client_error';
    $clientCode = playbackFailureCleanContext($_POST['client_code'] ?? '');
    $context = playbackFailureCleanContext($_POST['context'] ?? '');

    recordPlaybackFailure($songId, $errorType, 'client', [
        'client_code' => $clientCode,
        'context' => $context,
    ]);

    playbackFailureJson(true, '재생 실패를 기록했습니다.');
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'playback_failure_error', 'Playback failure report failed', [
            'error' => limitLogText($e->getMessage(), 300),
        ]);
    }
    playbackFailureJson(false, '재생 실패 기록 중 문제가 발생했습니다.', [], 500);
}
