import fs from 'fs-extra';
import path from 'path';
import { logger } from '../utils/logger';
import { getHttpClientTemplate } from '../templates/http-client';
import { 
  buildFilePath, 
  validateFileExists, 
  createDirectory, 
  writeFile 
} from '../utils/file-operations';
import type { FileSystem } from '../utils/file-operations';
import { 
  logError, 
  logSuccess, 
  logInfo 
} from '../utils/logging';
import type { Logger } from '../utils/logging';

interface HttpClientConfig {
  targetPath: string;
  template: string;
}

const buildHttpClientFilePath = (): string => 
  buildFilePath(process.cwd(), 'src/lib/http-client.ts');

const logHttpClientGenerationSuccess = (log: Logger, targetPath: string): void => {
  logSuccess(log, 'HTTP client generated successfully!');
  logInfo(log, 'Location: ' + targetPath);
  logInfo(log, '💡 You can now import it with: import { httpClient } from \'./lib/http-client\'');
};

export const createHttpClient = async (
  fileSystem: FileSystem = fs,
  log: Logger = logger,
  getTemplate: () => string = getHttpClientTemplate
): Promise<void> => {
  const config: HttpClientConfig = {
    targetPath: buildHttpClientFilePath(),
    template: getTemplate()
  };

  try {
    const fileExists = await fileSystem.exists(config.targetPath);
    if (fileExists) {
      logError(log, 'HTTP client already exists at ' + config.targetPath);
      return;
    }

    await fileSystem.ensureDir(path.dirname(config.targetPath));
    await fileSystem.writeFile(config.targetPath, config.template, 'utf8');
    logHttpClientGenerationSuccess(log, config.targetPath);
  } catch (error: unknown) {
    logError(log, `Error creating HTTP client: ${error instanceof Error ? error.message : 'Unknown error'}`);
  }
}; 