/**
 * CRUD Commands - Create, List, Show, Update, Delete operations
 *
 * Provides CLI commands for basic element operations:
 * - create: Create new elements (tasks, etc.)
 * - list: List elements with filtering
 * - show: Show detailed element information
 */
import { success, failure, ExitCode } from '../types.js';
import { getFormatter, getOutputMode, getStatusIcon, formatEventsTable } from '../formatter.js';
import { createTask, createDocument, ContentType, TaskStatus, TaskTypeValue, PlanStatus } from '@stoneforge/core';
import { createInboxService } from '../../services/inbox.js';
import { resolveActor, createAPI } from '../db.js';
export const createOptions = [
    {
        name: 'title',
        short: 't',
        description: 'Title for the element (required for tasks)',
        hasValue: true,
    },
    {
        name: 'name',
        short: 'n',
        description: 'Alias for --title',
        hasValue: true,
    },
    {
        name: 'priority',
        short: 'p',
        description: 'Priority level (1-5, 1=critical)',
        hasValue: true,
    },
    {
        name: 'complexity',
        short: 'c',
        description: 'Complexity level (1-5, 1=trivial)',
        hasValue: true,
    },
    {
        name: 'type',
        description: 'Task type (bug, feature, task, chore)',
        hasValue: true,
    },
    {
        name: 'assignee',
        short: 'a',
        description: 'Assignee entity ID',
        hasValue: true,
    },
    {
        name: 'tag',
        description: 'Add a tag (can be repeated)',
        hasValue: true,
        array: true,
    },
    {
        name: 'plan',
        description: 'Plan ID or name to attach this task to',
        hasValue: true,
    },
    {
        name: 'description',
        short: 'd',
        description: 'Task description (creates a linked document)',
        hasValue: true,
    },
];
export async function createHandler(args, options) {
    // First argument is the element type
    const [elementType] = args;
    if (!elementType) {
        return failure('Usage: sf task create [options]\n\nUse "sf task create --help" for options.', ExitCode.INVALID_ARGUMENTS);
    }
    // Currently only support task creation
    if (elementType !== 'task') {
        return failure(`Unsupported element type: ${elementType}. Currently supported: task`, ExitCode.INVALID_ARGUMENTS);
    }
    // Use --name as alias for --title
    const title = options.title ?? options.name;
    // Validate required options for task
    if (!title) {
        return failure('--title (or --name) is required for creating a task', ExitCode.INVALID_ARGUMENTS);
    }
    // Create command should create the database if it doesn't exist
    const { api, error } = createAPI(options, true);
    if (error) {
        return failure(error, ExitCode.GENERAL_ERROR);
    }
    try {
        const actor = resolveActor(options);
        // Parse priority
        let priority;
        if (options.priority) {
            const p = parseInt(options.priority, 10);
            if (isNaN(p) || p < 1 || p > 5) {
                return failure('Priority must be a number from 1 to 5', ExitCode.VALIDATION);
            }
            priority = p;
        }
        // Parse complexity
        let complexity;
        if (options.complexity) {
            const c = parseInt(options.complexity, 10);
            if (isNaN(c) || c < 1 || c > 5) {
                return failure('Complexity must be a number from 1 to 5', ExitCode.VALIDATION);
            }
            complexity = c;
        }
        let taskType;
        if (options.type) {
            const validTypes = Object.values(TaskTypeValue);
            if (!validTypes.includes(options.type)) {
                return failure(`Invalid task type: ${options.type}. Must be one of: ${validTypes.join(', ')}`, ExitCode.VALIDATION);
            }
            taskType = options.type;
        }
        // Handle tags (may come as array if --tag is specified multiple times)
        let tags;
        if (options.tag) {
            tags = Array.isArray(options.tag) ? options.tag : [options.tag];
        }
        // Handle description: create a document and link it to the task
        let descriptionRef;
        if (options.description) {
            const docInput = {
                content: options.description,
                contentType: ContentType.MARKDOWN,
                createdBy: actor,
            };
            const newDoc = await createDocument(docInput);
            const createdDoc = await api.create(newDoc);
            descriptionRef = createdDoc.id;
        }
        // Create task input (title is guaranteed non-null from validation above)
        const input = {
            title: title,
            createdBy: actor,
            ...(priority !== undefined && { priority }),
            ...(complexity !== undefined && { complexity }),
            ...(taskType !== undefined && { taskType }),
            ...(options.assignee && { assignee: options.assignee }),
            ...(tags && { tags }),
            ...(descriptionRef !== undefined && { descriptionRef }),
        };
        // Create the task
        const task = await createTask(input);
        // The API's create method expects ElementInput which Task satisfies
        const created = await api.create(task);
        // If --plan is provided, attach the task to the plan
        let planWarning;
        if (options.plan) {
            try {
                // First try to find by ID (if it looks like an element ID)
                let plan = null;
                if (options.plan.startsWith('el-') || options.plan.match(/^el[a-z0-9]+$/i)) {
                    plan = await api.get(options.plan);
                }
                // If not found by ID, search by title
                if (!plan) {
                    const plans = await api.list({ type: 'plan' });
                    plan = plans.find((p) => p.title === options.plan) ?? null;
                }
                if (!plan) {
                    planWarning = `Warning: Plan not found: ${options.plan}. Task was created but not attached to a plan.`;
                }
                else if (plan.type !== 'plan') {
                    planWarning = `Warning: ${options.plan} is not a plan (type: ${plan.type}). Task was created but not attached.`;
                }
                else if (plan.status === PlanStatus.CANCELLED) {
                    planWarning = `Warning: Plan ${plan.id} is cancelled. Task was created but not attached.`;
                }
                else {
                    await api.addTaskToPlan(created.id, plan.id, { actor });
                }
            }
            catch (attachErr) {
                const attachMessage = attachErr instanceof Error ? attachErr.message : String(attachErr);
                planWarning = `Warning: Failed to attach task to plan: ${attachMessage}. Task was created successfully.`;
            }
        }
        const message = planWarning
            ? `Created task ${created.id}\n${planWarning}`
            : `Created task ${created.id}`;
        return success(created, message);
    }
    catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        return failure(`Failed to create task: ${message}`, ExitCode.GENERAL_ERROR);
    }
}
export const createCommand = {
    name: 'create',
    description: 'Create a new element',
    usage: 'sf create <type> [options]',
    help: `Create a new element of the specified type.

Supported types:
  task     Work item with status, priority, and assignment

Task options:
  -t, --title <text>      Task title (required)
  -d, --description <text> Task description (creates a linked document)
  -p, --priority <1-5>    Priority (1=critical, 5=minimal, default=3)
  -c, --complexity <1-5>  Complexity (1=trivial, 5=very complex, default=3)
      --type <type>       Task type: bug, feature, task, chore
  -a, --assignee <id>     Assignee entity ID
      --tag <tag>         Add a tag (can be repeated)
      --plan <id|name>    Plan ID or name to attach this task to

Examples:
  sf create task --title "Fix login bug" --priority 1 --type bug
  sf create task -t "Add dark mode" --tag ui --tag feature
  sf create task -t "Implement feature X" --plan el-plan123
  sf create task -t "Implement feature X" --plan "My Plan Name"
  sf create task -t "New feature" -d "Detailed description here"`,
    options: createOptions,
    handler: createHandler,
};
export const listOptions = [
    {
        name: 'type',
        short: 't',
        description: 'Filter by element type',
        hasValue: true,
    },
    {
        name: 'status',
        short: 's',
        description: 'Filter by status (for tasks)',
        hasValue: true,
    },
    {
        name: 'priority',
        short: 'p',
        description: 'Filter by priority (for tasks)',
        hasValue: true,
    },
    {
        name: 'assignee',
        short: 'a',
        description: 'Filter by assignee (for tasks)',
        hasValue: true,
    },
    {
        name: 'tag',
        description: 'Filter by tag (can be repeated for AND)',
        hasValue: true,
        array: true,
    },
    {
        name: 'limit',
        short: 'l',
        description: 'Maximum number of results',
        hasValue: true,
    },
    {
        name: 'offset',
        short: 'o',
        description: 'Number of results to skip',
        hasValue: true,
    },
];
export async function listHandler(args, options) {
    const { api, error } = createAPI(options);
    if (error) {
        return failure(error, ExitCode.GENERAL_ERROR);
    }
    try {
        // Build filter from options
        const filter = {};
        // Type filter (can also be first positional arg)
        const typeArg = args[0] ?? options.type;
        if (typeArg) {
            filter.type = typeArg;
        }
        // Status filter
        if (options.status) {
            const validStatuses = Object.values(TaskStatus);
            if (!validStatuses.includes(options.status)) {
                return failure(`Invalid status: ${options.status}. Must be one of: ${validStatuses.join(', ')}`, ExitCode.VALIDATION);
            }
            filter.status = options.status;
        }
        // Priority filter
        if (options.priority) {
            const priority = parseInt(options.priority, 10);
            if (isNaN(priority) || priority < 1 || priority > 5) {
                return failure('Priority must be a number from 1 to 5', ExitCode.VALIDATION);
            }
            filter.priority = priority;
        }
        // Assignee filter
        if (options.assignee) {
            filter.assignee = options.assignee;
        }
        // Tag filter
        if (options.tag) {
            filter.tags = Array.isArray(options.tag) ? options.tag : [options.tag];
        }
        // Pagination
        if (options.limit) {
            const limit = parseInt(options.limit, 10);
            if (isNaN(limit) || limit < 1) {
                return failure('Limit must be a positive number', ExitCode.VALIDATION);
            }
            filter.limit = limit;
        }
        if (options.offset) {
            const offset = parseInt(options.offset, 10);
            if (isNaN(offset) || offset < 0) {
                return failure('Offset must be a non-negative number', ExitCode.VALIDATION);
            }
            filter.offset = offset;
        }
        // Query elements
        const result = await api.listPaginated(filter);
        // Format output based on mode
        const mode = getOutputMode(options);
        const formatter = getFormatter(mode);
        if (mode === 'json') {
            return success(result.items);
        }
        if (mode === 'quiet') {
            return success(result.items.map((e) => e.id).join('\n'));
        }
        // Human-readable output
        if (result.items.length === 0) {
            return success(null, 'No elements found');
        }
        // Sort by priority ASC for tasks (P1 is highest priority, comes first)
        const sortedItems = [...result.items].sort((a, b) => {
            const dataA = a;
            const dataB = b;
            const priorityA = typeof dataA.priority === 'number' ? dataA.priority : 999;
            const priorityB = typeof dataB.priority === 'number' ? dataB.priority : 999;
            return priorityA - priorityB;
        });
        // Build table data with priority and assignee columns
        const headers = ['ID', 'TYPE', 'TITLE/NAME', 'STATUS', 'PRIORITY', 'ASSIGNEE', 'CREATED'];
        const rows = sortedItems.map((item) => {
            const data = item;
            const title = data.title ?? data.name ?? '-';
            const status = data.status ? `${getStatusIcon(data.status)} ${data.status}` : '-';
            const priority = typeof data.priority === 'number' ? `P${data.priority}` : '-';
            const assignee = typeof data.assignee === 'string' ? data.assignee : '-';
            const created = item.createdAt.split('T')[0];
            return [item.id, item.type, title, status, priority, assignee, created];
        });
        const table = formatter.table(headers, rows);
        const summary = `\nShowing ${result.items.length} of ${result.total} elements`;
        return success(result.items, table + summary);
    }
    catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        return failure(`Failed to list elements: ${message}`, ExitCode.GENERAL_ERROR);
    }
}
export const listCommand = {
    name: 'list',
    description: 'List elements',
    usage: 'sf list [type] [options]',
    help: `List elements with optional filtering.

Arguments:
  type                  Element type to list (task, document, etc.)

Options:
  -t, --type <type>     Filter by element type
  -s, --status <status> Filter by status (for tasks)
  -p, --priority <1-5>  Filter by priority (for tasks)
  -a, --assignee <id>   Filter by assignee (for tasks)
      --tag <tag>       Filter by tag (can be repeated)
  -l, --limit <n>       Maximum results (default: 50)
  -o, --offset <n>      Skip first n results

Examples:
  sf list task
  sf list task --status open
  sf list --type task --priority 1 --status in_progress
  sf list --tag urgent`,
    options: listOptions,
    handler: listHandler,
};
export const showOptions = [
    {
        name: 'events',
        short: 'e',
        description: 'Include recent events/history',
        hasValue: false,
    },
    {
        name: 'events-limit',
        description: 'Maximum number of events to show (default: 10)',
        hasValue: true,
    },
];
export async function showHandler(args, options) {
    const [id] = args;
    if (!id) {
        return failure('Usage: sf show <id>', ExitCode.INVALID_ARGUMENTS);
    }
    const { api, backend, error } = createAPI(options);
    if (error) {
        return failure(error, ExitCode.GENERAL_ERROR);
    }
    try {
        // Handle inbox item IDs (e.g., inbox-abc123)
        if (id.startsWith('inbox-')) {
            const inboxService = createInboxService(backend);
            const inboxItem = inboxService.getInboxItem(id);
            if (!inboxItem) {
                return failure(`Inbox item not found: ${id}`, ExitCode.NOT_FOUND);
            }
            // Fetch the associated message with hydrated content
            const message = await api.get(inboxItem.messageId, {
                hydrate: { content: true }
            });
            // Build a combined result with inbox item info and message content
            const result = {
                ...inboxItem,
                messageContent: message?.content ?? null,
                messageSender: message?.sender ?? null,
            };
            const mode = getOutputMode(options);
            const formatter = getFormatter(mode);
            if (mode === 'json') {
                return success(result);
            }
            if (mode === 'quiet') {
                return success(inboxItem.id);
            }
            // Human-readable output
            const output = formatter.element(result);
            return success(result, output);
        }
        // Get the element
        const element = await api.get(id);
        if (!element) {
            return failure(`Element not found: ${id}`, ExitCode.NOT_FOUND);
        }
        // Check if element is deleted (tombstone)
        const data = element;
        if (data.status === 'tombstone' || data.deletedAt) {
            return failure(`Element not found: ${id}`, ExitCode.NOT_FOUND);
        }
        // Format output based on mode
        const mode = getOutputMode(options);
        const formatter = getFormatter(mode);
        // Get events if requested
        let events;
        if (options.events) {
            const eventsLimit = options['events-limit'] ? parseInt(options['events-limit'], 10) : 10;
            events = await api.getEvents(id, { limit: eventsLimit });
        }
        // Get plan progress if element is a plan
        let planProgress;
        if (element.type === 'plan') {
            try {
                planProgress = await api.getPlanProgress(id);
            }
            catch {
                // Ignore errors fetching progress
            }
        }
        if (mode === 'json') {
            if (events || planProgress) {
                return success({ element, ...(planProgress && { progress: planProgress }), ...(events && { events }) });
            }
            return success(element);
        }
        if (mode === 'quiet') {
            return success(element.id);
        }
        // Human-readable output - format as key-value pairs
        let output = formatter.element(element);
        // Add plan progress if available
        if (planProgress) {
            output += '\n\n--- Task Progress ---\n';
            output += `Total:       ${planProgress.totalTasks}\n`;
            output += `Completed:   ${planProgress.completedTasks}\n`;
            output += `In Progress: ${planProgress.inProgressTasks}\n`;
            output += `Blocked:     ${planProgress.blockedTasks}\n`;
            output += `Ready:       ${planProgress.remainingTasks}\n`;
            output += `Progress:    ${planProgress.completionPercentage}%`;
        }
        // Add events if requested
        if (events && events.length > 0) {
            output += '\n\n--- Recent Events ---\n';
            output += formatEventsTable(events);
        }
        else if (options.events) {
            output += '\n\n--- Recent Events ---\nNo events';
        }
        return success(element, output);
    }
    catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        return failure(`Failed to get element: ${message}`, ExitCode.GENERAL_ERROR);
    }
}
export const showCommand = {
    name: 'show',
    description: 'Show element details',
    usage: 'sf show <id> [options]',
    help: `Display detailed information about an element.

Arguments:
  id    Element identifier (e.g., el-abc123) or inbox item ID (e.g., inbox-abc123)

Options:
  -e, --events            Include recent events/history
      --events-limit <n>  Maximum events to show (default: 10)

Examples:
  sf show el-abc123
  sf show el-abc123 --events
  sf show el-abc123 --events --events-limit 20
  sf show el-abc123 --json
  sf show inbox-abc123     # Show inbox item with message content`,
    options: showOptions,
    handler: showHandler,
};
export const updateOptions = [
    {
        name: 'title',
        short: 't',
        description: 'New title',
        hasValue: true,
    },
    {
        name: 'priority',
        short: 'p',
        description: 'New priority level (1-5)',
        hasValue: true,
    },
    {
        name: 'complexity',
        short: 'c',
        description: 'New complexity level (1-5)',
        hasValue: true,
    },
    {
        name: 'status',
        short: 's',
        description: 'New status (for tasks: open, in_progress, closed, deferred)',
        hasValue: true,
    },
    {
        name: 'assignee',
        short: 'a',
        description: 'New assignee (use empty string to unassign)',
        hasValue: true,
    },
    {
        name: 'tag',
        description: 'Replace all tags (can be repeated)',
        hasValue: true,
        array: true,
    },
    {
        name: 'add-tag',
        description: 'Add a tag (can be repeated)',
        hasValue: true,
        array: true,
    },
    {
        name: 'remove-tag',
        description: 'Remove a tag (can be repeated)',
        hasValue: true,
        array: true,
    },
];
export async function updateHandler(args, options) {
    const [id] = args;
    if (!id) {
        return failure('Usage: sf update <id> [options]', ExitCode.INVALID_ARGUMENTS);
    }
    const { api, error } = createAPI(options);
    if (error) {
        return failure(error, ExitCode.GENERAL_ERROR);
    }
    try {
        // Get existing element
        const element = await api.get(id);
        if (!element) {
            return failure(`Element not found: ${id}`, ExitCode.NOT_FOUND);
        }
        // Check if element is deleted (tombstone)
        const elemData = element;
        if (elemData.status === 'tombstone' || elemData.deletedAt) {
            return failure(`Element not found: ${id}`, ExitCode.NOT_FOUND);
        }
        // Build updates object
        const updates = {};
        // Handle title
        if (options.title !== undefined) {
            updates.title = options.title;
        }
        // Handle priority (for tasks)
        if (options.priority !== undefined) {
            if (element.type !== 'task') {
                return failure('Priority can only be set on tasks', ExitCode.VALIDATION);
            }
            const p = parseInt(options.priority, 10);
            if (isNaN(p) || p < 1 || p > 5) {
                return failure('Priority must be a number from 1 to 5', ExitCode.VALIDATION);
            }
            updates.priority = p;
        }
        // Handle complexity (for tasks)
        if (options.complexity !== undefined) {
            if (element.type !== 'task') {
                return failure('Complexity can only be set on tasks', ExitCode.VALIDATION);
            }
            const c = parseInt(options.complexity, 10);
            if (isNaN(c) || c < 1 || c > 5) {
                return failure('Complexity must be a number from 1 to 5', ExitCode.VALIDATION);
            }
            updates.complexity = c;
        }
        // Handle status (for tasks)
        if (options.status !== undefined) {
            if (element.type !== 'task') {
                return failure('Status can only be set on tasks', ExitCode.VALIDATION);
            }
            const validStatuses = Object.values(TaskStatus);
            if (!validStatuses.includes(options.status)) {
                return failure(`Invalid status: ${options.status}. Must be one of: ${validStatuses.join(', ')}`, ExitCode.VALIDATION);
            }
            updates.status = options.status;
        }
        // Handle assignee (for tasks)
        if (options.assignee !== undefined) {
            if (element.type !== 'task') {
                return failure('Assignee can only be set on tasks', ExitCode.VALIDATION);
            }
            // Empty string means unassign
            updates.assignee = options.assignee === '' ? undefined : options.assignee;
        }
        // Handle tag operations
        let currentTags = element.tags ?? [];
        // Complete replacement with --tag
        if (options.tag !== undefined) {
            const tags = Array.isArray(options.tag) ? options.tag : [options.tag];
            currentTags = tags;
        }
        // Add tags with --add-tag
        if (options['add-tag'] !== undefined) {
            const tagsToAdd = Array.isArray(options['add-tag']) ? options['add-tag'] : [options['add-tag']];
            const tagSet = new Set(currentTags);
            for (const tag of tagsToAdd) {
                tagSet.add(tag);
            }
            currentTags = Array.from(tagSet);
        }
        // Remove tags with --remove-tag
        if (options['remove-tag'] !== undefined) {
            const tagsToRemove = Array.isArray(options['remove-tag']) ? options['remove-tag'] : [options['remove-tag']];
            const removeSet = new Set(tagsToRemove);
            currentTags = currentTags.filter(tag => !removeSet.has(tag));
        }
        // Only update tags if any tag option was used
        if (options.tag !== undefined || options['add-tag'] !== undefined || options['remove-tag'] !== undefined) {
            updates.tags = currentTags;
        }
        // Check if there are any updates to apply
        if (Object.keys(updates).length === 0) {
            return failure('No updates specified. Use --help for available options.', ExitCode.INVALID_ARGUMENTS);
        }
        // Resolve actor for audit trail
        const actor = resolveActor(options);
        // Apply the update with optimistic concurrency control
        const updated = await api.update(id, updates, {
            actor,
            expectedUpdatedAt: element.updatedAt,
        });
        // Format output based on mode
        const mode = getOutputMode(options);
        const formatter = getFormatter(mode);
        if (mode === 'json') {
            return success(updated);
        }
        if (mode === 'quiet') {
            return success(updated.id);
        }
        // Human-readable output
        const output = formatter.element(updated);
        return success(updated, `Updated ${element.type} ${id}\n\n${output}`);
    }
    catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        return failure(`Failed to update element: ${message}`, ExitCode.GENERAL_ERROR);
    }
}
export const updateCommand = {
    name: 'update',
    description: 'Update an element',
    usage: 'sf update <id> [options]',
    help: `Update fields on an existing element.

Arguments:
  id    Element identifier (e.g., el-abc123)

Options:
  -t, --title <text>       New title
  -p, --priority <1-5>     New priority (tasks only)
  -c, --complexity <1-5>   New complexity (tasks only)
  -s, --status <status>    New status (tasks only: open, in_progress, closed, deferred)
  -a, --assignee <id>      New assignee (tasks only, empty string to unassign)
      --tag <tag>          Replace all tags (can be repeated)
      --add-tag <tag>      Add a tag (can be repeated)
      --remove-tag <tag>   Remove a tag (can be repeated)

Examples:
  sf update el-abc123 --title "New Title"
  sf update el-abc123 --priority 1 --status in_progress
  sf update el-abc123 --add-tag urgent --add-tag frontend
  sf update el-abc123 --remove-tag old-tag
  sf update el-abc123 --assignee ""  # Unassign`,
    options: updateOptions,
    handler: updateHandler,
};
export const deleteOptions = [
    {
        name: 'reason',
        short: 'r',
        description: 'Deletion reason',
        hasValue: true,
    },
    {
        name: 'force',
        short: 'f',
        description: 'Skip confirmation (for scripts)',
    },
];
export async function deleteHandler(args, options) {
    const [id] = args;
    if (!id) {
        return failure('Usage: sf delete <id> [options]', ExitCode.INVALID_ARGUMENTS);
    }
    const { api, error } = createAPI(options);
    if (error) {
        return failure(error, ExitCode.GENERAL_ERROR);
    }
    try {
        // Get existing element to verify it exists and get its type
        const element = await api.get(id);
        if (!element) {
            return failure(`Element not found: ${id}`, ExitCode.NOT_FOUND);
        }
        // Check if element is already deleted (tombstone)
        const elemData = element;
        if (elemData.status === 'tombstone' || elemData.deletedAt) {
            return failure(`Element not found: ${id}`, ExitCode.NOT_FOUND);
        }
        // Check if element type supports deletion
        if (element.type === 'message') {
            return failure('Messages cannot be deleted (immutable)', ExitCode.VALIDATION);
        }
        // Resolve actor for audit trail
        const actor = resolveActor(options);
        // Perform the soft delete
        await api.delete(id, { actor, reason: options.reason });
        // Format output based on mode
        const mode = getOutputMode(options);
        if (mode === 'json') {
            return success({ id, deleted: true, type: element.type });
        }
        if (mode === 'quiet') {
            return success(id);
        }
        return success({ id, deleted: true }, `Deleted ${element.type} ${id}`);
    }
    catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        return failure(`Failed to delete element: ${message}`, ExitCode.GENERAL_ERROR);
    }
}
export const deleteCommand = {
    name: 'delete',
    description: 'Delete an element',
    usage: 'sf delete <id> [options]',
    help: `Soft-delete an element.

The element will be marked as deleted (tombstone) but not immediately removed.
Tombstones are retained for a configurable period (default: 30 days) to
allow sync operations to propagate deletions.

Note: Messages cannot be deleted as they are immutable.

Arguments:
  id    Element identifier (e.g., el-abc123)

Options:
  -r, --reason <text>    Deletion reason (recorded in audit trail)
  -f, --force            Skip confirmation (for scripts)

Examples:
  sf delete el-abc123
  sf delete el-abc123 --reason "Duplicate entry"
  sf delete el-abc123 -f`,
    options: deleteOptions,
    handler: deleteHandler,
};
//# sourceMappingURL=crud.js.map