import { Command } from 'commander';
import type { ApiClient } from '../api-client.js';
import { resolveResource, resolveNameOrId } from './shared.js';

export interface DeleteCommandDeps {
  client: ApiClient;
  log: (...args: unknown[]) => void;
}

export function createDeleteCommand(deps: DeleteCommandDeps): Command {
  const { client, log } = deps;

  return new Command('delete')
    .description('Delete a resource (server, instance, secret, project, user, group, rbac)')
    .argument('<resource>', 'resource type')
    .argument('<id>', 'resource ID or name')
    .option('-p, --project <name>', 'Project name (for serverattachment)')
    .action(async (resourceArg: string, idOrName: string, opts: { project?: string }) => {
      const resource = resolveResource(resourceArg);

      // Serverattachments: delete serverattachment <server> --project <project>
      if (resource === 'serverattachments') {
        if (!opts.project) {
          throw new Error('--project is required. Usage: mcpctl delete serverattachment <server> --project <name>');
        }
        const projectId = await resolveNameOrId(client, 'projects', opts.project);
        await client.delete(`/api/v1/projects/${projectId}/servers/${idOrName}`);
        log(`server '${idOrName}' detached from project '${opts.project}'`);
        return;
      }

      // Resolve name → ID for any resource type
      let id: string;
      try {
        id = await resolveNameOrId(client, resource, idOrName);
      } catch {
        id = idOrName; // Fall through with original
      }

      await client.delete(`/api/v1/${resource}/${id}`);

      const singular = resource.replace(/s$/, '');
      log(`${singular} '${idOrName}' deleted.`);
    });
}
