<?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();

$songId = isset($_POST['song_id']) ? (int)$_POST['song_id'] : (isset($_POST['id']) ? (int)$_POST['id'] : 0);
if ($songId <= 0) {
    apiError('올바르지 않은 곡 ID입니다.', 'invalid_song_id', 400);
}

try {
    $pdo = getDBConnection();
    $checkStmt = $pdo->prepare("SELECT id FROM songs WHERE id = :id AND COALESCE(is_missing, 0) = 0 LIMIT 1");
    $checkStmt->execute([':id' => $songId]);
    if (!$checkStmt->fetch()) {
        apiError('곡을 찾을 수 없습니다.', 'song_not_found', 404);
    }

    $likeStmt = $pdo->prepare("SELECT id FROM liked_songs WHERE song_id = :song_id LIMIT 1");
    $likeStmt->execute([':song_id' => $songId]);
    $likeRecord = $likeStmt->fetch();

    $liked = false;
    if ($likeRecord) {
        $deleteStmt = $pdo->prepare("DELETE FROM liked_songs WHERE song_id = :song_id");
        $deleteStmt->execute([':song_id' => $songId]);
        $message = '좋아요를 취소했습니다.';
    } else {
        $insertStmt = $pdo->prepare("INSERT INTO liked_songs (song_id) VALUES (:song_id)");
        $insertStmt->execute([':song_id' => $songId]);
        $liked = true;
        $message = '좋아요한 곡에 등록했습니다.';
    }

    apiSuccess([
        'song_id' => $songId,
        'liked' => $liked,
    ], $message, [], [
        'liked' => $liked,
    ]);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'like_error', 'Like API failed', ['song_id' => $songId, 'error' => $e->getMessage()]);
    }
    apiError('좋아요 상태를 변경하지 못했습니다.', 'server_error', 500);
}
