<?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/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;
$songId = isset($_POST['song_id']) ? (int)$_POST['song_id'] : 0;

if ($playlistId <= 0 || $songId <= 0) {
    apiError('요청 값이 올바르지 않습니다.', 'invalid_request', 400);
}

try {
    $pdo = getDBConnection();

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

    $songCheck = $pdo->prepare("SELECT id FROM songs WHERE id = :id AND COALESCE(is_missing, 0) = 0 LIMIT 1");
    $songCheck->execute([':id' => $songId]);
    if (!$songCheck->fetch()) {
        apiError('재생할 수 없는 곡입니다.', 'song_not_found', 404);
    }

    $dupCheck = $pdo->prepare("SELECT id FROM playlist_songs WHERE playlist_id = :playlist_id AND song_id = :song_id LIMIT 1");
    $dupCheck->execute([':playlist_id' => $playlistId, ':song_id' => $songId]);
    if ($dupCheck->fetch()) {
        apiError('이미 이 플레이리스트에 있는 곡입니다.', 'playlist_duplicate_song', 409);
    }

    $orderStmt = $pdo->prepare("SELECT COALESCE(MAX(sort_order), 0) + 1 FROM playlist_songs WHERE playlist_id = :playlist_id");
    $orderStmt->execute([':playlist_id' => $playlistId]);
    $nextOrder = (int)$orderStmt->fetchColumn();

    $insertStmt = $pdo->prepare("
        INSERT INTO playlist_songs (playlist_id, song_id, sort_order)
        VALUES (:playlist_id, :song_id, :sort_order)
    ");
    $insertStmt->execute([
        ':playlist_id' => $playlistId,
        ':song_id' => $songId,
        ':sort_order' => $nextOrder,
    ]);

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

    apiSuccess([
        'playlist_id' => $playlistId,
        'song_id' => $songId,
        'sort_order' => $nextOrder,
    ], '플레이리스트에 곡을 추가했습니다.');
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'playlist_error', 'Playlist add failed', [
            'playlist_id' => $playlistId,
            'song_id' => $songId,
            'error' => $e->getMessage(),
        ]);
    }
    apiError('플레이리스트에 곡을 추가하지 못했습니다.', 'server_error', 500);
}
