import * as fs from 'node:fs';
import * as path from 'node:path';
import { packageNameToPath, resolvePackagesNodeModulesRoot } from '../utils/package-store.js';

export interface IUninstallCommandOptions {
  readonly cwd?: string;
  readonly packagesDir?: string;
}

export interface IUninstallCommandResult {
  readonly packageName: string;
  readonly removedPath: string;
}

export async function uninstallCommand(packageName: string, options: IUninstallCommandOptions = {}): Promise<IUninstallCommandResult> {
  const cwd = path.resolve(options.cwd ?? process.cwd());
  const nodeModulesRoot = resolvePackagesNodeModulesRoot(cwd, options.packagesDir);
  const removedPath = path.join(nodeModulesRoot, packageNameToPath(packageName));

  if (!fs.existsSync(removedPath)) {
    throw new Error(`Package is not installed: ${packageName}`);
  }

  fs.rmSync(removedPath, { recursive: true, force: true });
  return { packageName, removedPath };
}
