// services/provider-registry.js
// Simple provider registry/factory to resolve adapters by provider key.

const GithubIntegrationService = require('./github-integration.service');
const GitlabAdapter = require('./providers/gitlab.adapter');
const BitbucketAdapter = require('./providers/bitbucket.adapter');
const GiteaAdapter = require('./providers/gitea.adapter');

class GithubAdapter {
  constructor() {
    this.impl = new GithubIntegrationService();
  }

  parseRepoUrl(url) {
    return this.impl.parseGitHubUrl(url);
  }

  async checkRepositoryAccess(owner, repo) {
    return await this.impl.checkRepositoryAccess(owner, repo);
  }

  async fetchRepositoryMetadata(owner, repo) {
    return await this.impl.fetchRepositoryMetadata(owner, repo);
  }

  async analyzeCodebase(owner, repo, branch) {
    return await this.impl.analyzeCodebase(owner, repo, branch);
  }

  async ensureRepositoryWebhook(owner, repo, callbackUrl) {
    return await this.impl.ensureRepositoryWebhook(owner, repo, callbackUrl);
  }

  async syncRepositoryWithGit(owner, repo, branch, repositoryId) {
    return await this.impl.syncRepositoryWithGit(owner, repo, branch, repositoryId);
  }

  async downloadRepositoryWithStorage(owner, repo, branch, repositoryId) {
    return await this.impl.downloadRepositoryWithStorage(owner, repo, branch, repositoryId);
  }

  async syncRepositoryWithFallback(owner, repo, branch, repositoryId) {
    return await this.impl.syncRepositoryWithFallback(owner, repo, branch, repositoryId);
  }

  async getRepositoryDiff(owner, repo, branch, fromSha, toSha) {
    return await this.impl.getRepositoryDiff(owner, repo, branch, fromSha, toSha);
  }

  async getRepositoryChangesSince(owner, repo, branch, sinceSha) {
    return await this.impl.getRepositoryChangesSince(owner, repo, branch, sinceSha);
  }

  async cleanupRepositoryStorage(repositoryId) {
    return await this.impl.cleanupRepositoryStorage(repositoryId);
  }
}

class ProviderRegistry {
  constructor() {
    this.providers = new Map();
    // Register GitHub by default
    this.providers.set('github', () => new GithubAdapter());
    this.providers.set('gitlab', () => new GitlabAdapter());
    this.providers.set('bitbucket', () => new BitbucketAdapter());
    this.providers.set('gitea', () => new GiteaAdapter());
  }

  register(providerKey, factoryFn) {
    this.providers.set(providerKey, factoryFn);
  }

  resolve(providerKey) {
    const factory = this.providers.get((providerKey || '').toLowerCase());
    if (!factory) {
      throw new Error(`Unsupported provider: ${providerKey}`);
    }
    return factory();
  }
}

module.exports = new ProviderRegistry();


