<?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/functions_tags.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => '허용되지 않는 요청입니다.'], JSON_UNESCAPED_UNICODE);
    exit;
}
if (!verifyCsrfToken()) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => '요청 토큰이 올바르지 않습니다.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$action = $_POST['action'] ?? '';
$songId = isset($_POST['song_id']) ? (int)$_POST['song_id'] : 0;

try {
    if ($action === 'add') {
        $tagName = trim((string)($_POST['tag_name'] ?? ''));
        if ($songId <= 0 || $tagName === '') throw new RuntimeException('태그 이름을 입력해 주세요.');
        addTagToSong($songId, $tagName);
        echo json_encode(['success' => true, 'message' => '태그를 추가했습니다.', 'tags' => getSongTags($songId)], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if ($action === 'remove') {
        $tagId = isset($_POST['tag_id']) ? (int)$_POST['tag_id'] : 0;
        if ($songId <= 0 || $tagId <= 0) throw new RuntimeException('요청 값이 올바르지 않습니다.');
        removeTagFromSong($songId, $tagId);
        echo json_encode(['success' => true, 'message' => '태그를 제거했습니다.', 'tags' => getSongTags($songId)], JSON_UNESCAPED_UNICODE);
        exit;
    }
    throw new RuntimeException('알 수 없는 요청입니다.');
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'tag_error', 'Song tag action failed', ['action' => $action, 'song_id' => $songId, 'error' => $e->getMessage()]);
    }
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
}
