<?php
declare(strict_types=1);

require_once __DIR__ . '/../../includes/bootstrap.php';
require_once __DIR__ . '/../../includes/CaseResults.php';

dbnToolsRequireMethod('POST');
dbnToolsRequireAuth();

if (!dbnToolsIsFreeTier()) {
    dbnToolsError('Saved analyses are SSO-only.', 403, 'sso_only');
}

$userId = (int)($_SESSION['dbn_tools_sso_uid'] ?? 0);
if ($userId <= 0) {
    dbnToolsError('Missing user id.', 401, 'no_user');
}

$input  = dbnToolsJsonInput(4000);
$action = (string)($input['action'] ?? '');
$id     = (int)($input['id'] ?? 0);

if ($id <= 0) {
    dbnToolsError('Missing result id.', 422, 'missing_id');
}

switch ($action) {
    case 'pin':
        $pinned = CaseResults::togglePin($userId, $id);
        if ($pinned === null) {
            dbnToolsError('Result not found.', 404, 'not_found');
        }
        dbnToolsRespond(['ok' => true, 'pinned' => $pinned]);
        break;

    case 'delete':
        if (!CaseResults::softDelete($userId, $id)) {
            dbnToolsError('Result not found or already deleted.', 404, 'not_found');
        }
        dbnToolsRespond(['ok' => true]);
        break;

    case 'rename':
        $title = (string)($input['title'] ?? '');
        if (!CaseResults::updateTitle($userId, $id, $title)) {
            dbnToolsError('Could not rename — empty title or result not found.', 422, 'rename_failed');
        }
        dbnToolsRespond(['ok' => true]);
        break;

    default:
        dbnToolsError('Unknown action.', 422, 'unknown_action');
}
