import { z } from 'zod';
import { createCommand } from '../../../types';
import * as tui from '../../../tui';
import { createStorageAdapter } from './util';
import { getCommand } from '../../../command-prefix';
const KVDeleteResponseSchema = z.object({
	success: z.boolean().describe('Whether the operation succeeded'),
	namespace: z.string().describe('Namespace name'),
	key: z.string().describe('Key name'),
	durationMs: z.number().describe('Operation duration in milliseconds'),
});

export const deleteSubcommand = createCommand({
	name: 'delete',
	aliases: ['rm', 'del', 'remove', 'terminate'],
	description: 'Delete a key from the keyvalue storage',
	tags: ['destructive', 'deletes-resource', 'slow', 'requires-auth'],
	idempotent: true,
	requires: { auth: true, region: true },
	optional: { project: true },
	examples: [
		{
			command: getCommand('cloud kv delete production user:123'),
			description: 'Delete user data',
		},
		{
			command: getCommand('cloud kv delete cache session:abc'),
			description: 'Delete cached session',
		},
		{
			command: getCommand('cloud kv rm staging cache:homepage'),
			description: 'Delete homepage cache (using alias)',
		},
	],
	schema: {
		args: z.object({
			namespace: z.string().min(1).describe('the namespace name'),
			key: z.string().min(1).describe('the key name'),
		}),
		response: KVDeleteResponseSchema,
	},

	async handler(ctx) {
		const { args } = ctx;
		const started = Date.now();
		const storage = await createStorageAdapter(ctx);
		await storage.delete(args.namespace, args.key);
		const durationMs = Date.now() - started;
		if (!ctx.options.json) {
			tui.success(`deleted in ${durationMs.toFixed(1)}ms`);
		}

		return {
			success: true,
			namespace: args.namespace,
			key: args.key,
			durationMs,
		};
	},
});

export default deleteSubcommand;
