// services/providers/gitea.adapter.js
const VcsProviderInterface = require('../vcs-provider.interface');
const FileStorageService = require('../file-storage.service');
const GitRepoService = require('../git-repo.service');
const GiteaOAuthService = require('../gitea-oauth');

class GiteaAdapter extends VcsProviderInterface {
  constructor() {
    super();
    this.fileStorageService = new FileStorageService();
    this.gitRepoService = new GitRepoService();
    this.host = process.env.GITEA_BASE_URL || 'gitea.com';
    this.oauth = new GiteaOAuthService();
  }

  parseRepoUrl(url) {
    if (!url || typeof url !== 'string') throw new Error('URL must be a non-empty string');
    let normalized = url.trim();
    if (!normalized.startsWith('http')) normalized = 'https://' + normalized;
    const host = normalized.replace(/^https?:\/\//, '').split('/')[0];
    // Gitea can be self-hosted; accept any host when explicitly using /api/vcs/gitea
    const parts = normalized.split(host)[1].replace(/^\//, '').split('#')[0].split('?')[0].split('/');
    const owner = parts[0];
    const repo = (parts[1] || '').replace(/\.git$/, '');
    if (!owner || !repo) throw new Error(`Invalid Gitea repository URL: ${url}`);
    let branch = 'main';
    const treeIdx = parts.findIndex(p => p === 'tree');
    if (treeIdx >= 0 && parts[treeIdx + 1]) branch = parts[treeIdx + 1];
    return { owner, repo, branch };
  }

  async checkRepositoryAccess(owner, repo) {
    const token = await this.oauth.getToken();
    const base = (process.env.GITEA_BASE_URL || 'https://gitea.com').replace(/\/$/, '');
    
    try {
      // Always try with authentication first (like GitHub behavior)
      if (token?.access_token) {
        const resp = await fetch(`${base}/api/v1/repos/${owner}/${repo}`, { headers: { Authorization: `Bearer ${token.access_token}` } });
        if (resp.status === 200) {
          const d = await resp.json();
          const isPrivate = !!d.private;
          return { exists: true, isPrivate, hasAccess: true, requiresAuth: isPrivate };
        }
      }
      
      // No token or token failed: try without authentication
      const resp = await fetch(`${base}/api/v1/repos/${owner}/${repo}`);
      if (resp.status === 200) {
        const d = await resp.json();
        return { exists: true, isPrivate: !!d.private, hasAccess: true, requiresAuth: false };
      }
      if (resp.status === 404 || resp.status === 403) {
        // Repository exists but requires authentication (like GitHub behavior)
        return { exists: resp.status !== 404 ? true : false, isPrivate: true, hasAccess: false, requiresAuth: true };
      }
    } catch (error) {
      // If any error occurs, assume repository requires authentication
      return { exists: false, isPrivate: null, hasAccess: false, requiresAuth: true, error: 'Repository not found or requires authentication' };
    }
    
    return { exists: false, isPrivate: null, hasAccess: false, requiresAuth: true, error: 'Repository not found or requires authentication' };
  }

  async fetchRepositoryMetadata(owner, repo) {
    const token = await this.oauth.getToken();
    const base = (process.env.GITEA_BASE_URL || 'https://gitea.com').replace(/\/$/, '');
    if (token?.access_token) {
      try {
        const resp = await fetch(`${base}/api/v1/repos/${owner}/${repo}`, { headers: { Authorization: `Bearer ${token.access_token}` } });
        if (resp.ok) {
          const d = await resp.json();
          return { full_name: d.full_name || `${owner}/${repo}`, visibility: d.private ? 'private' : 'public', default_branch: d.default_branch || 'main', updated_at: d.updated_at };
        }
      } catch (_) {}
    }
    return { full_name: `${owner}/${repo}`, visibility: 'public', default_branch: 'main', updated_at: new Date().toISOString() };
  }

  async analyzeCodebase(owner, repo, branch) {
    return { total_files: 0, total_size: 0, directories: [], branch };
  }

  async ensureRepositoryWebhook(owner, repo, callbackUrl) {
    try {
      if (!callbackUrl) return { created: false, reason: 'missing_callback_url' };
      const token = await this.oauth.getToken();
      if (!token?.access_token) return { created: false, reason: 'missing_token' };
      const base = (process.env.GITEA_BASE_URL || 'https://gitea.com').replace(/\/$/, '');
      const secret = process.env.GITEA_WEBHOOK_SECRET || '';
      const resp = await fetch(`${base}/api/v1/repos/${owner}/${repo}/hooks`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token.access_token}` },
        body: JSON.stringify({ type: 'gitea', config: { url: callbackUrl, content_type: 'json', secret: secret || undefined }, events: ['push'], active: true })
      });
      if (resp.ok) { const d = await resp.json(); return { created: true, hook_id: d.id }; }
      return { created: false, reason: `status_${resp.status}` };
    } catch (e) {
      return { created: false, error: e.message };
    }
  }

  async syncRepositoryWithGit(owner, repo, branch, repositoryId) {
    const database = require('../../config/database');
    let storageRecord = null;
    try {
      const token = await this.oauth.getToken();
      let repoPath = null;
      if (token?.access_token) {
        repoPath = await this.gitRepoService.cloneIfMissingWithAuth(owner, repo, branch, this.host, token.access_token, 'oauth2');
      } else {
        repoPath = await this.gitRepoService.cloneIfMissingWithHost(owner, repo, branch, this.host);
      }
      storageRecord = await this.fileStorageService.initializeRepositoryStorage(repositoryId, repoPath);
      await this.fileStorageService.processDirectoryStructure(storageRecord.id, repositoryId, repoPath);
      const finalStorage = await this.fileStorageService.completeRepositoryStorage(storageRecord.id);
      
      // Get the current HEAD commit SHA and update the repository record
      try {
        const headSha = await this.gitRepoService.getHeadSha(repoPath);
        await database.query(
          'UPDATE github_repositories SET last_synced_at = NOW(), last_synced_commit_sha = $1, updated_at = NOW() WHERE id = $2',
          [headSha, repositoryId]
        );
      } catch (e) {
        // If we can't get the SHA, still update the sync time
        await database.query(
          'UPDATE github_repositories SET last_synced_at = NOW(), updated_at = NOW() WHERE id = $1',
          [repositoryId]
        );
      }
      return { success: true, method: 'git', targetDir: repoPath, storage: finalStorage };
    } catch (e) {
      if (storageRecord) await this.fileStorageService.markStorageFailed(storageRecord.id, e.message);
      return { success: false, error: e.message };
    }
  }

  async downloadRepositoryWithStorage() {
    return { success: false, error: 'api_download_not_implemented' };
  }

  async syncRepositoryWithFallback(owner, repo, branch, repositoryId) {
    const git = await this.syncRepositoryWithGit(owner, repo, branch, repositoryId);
    if (git.success) return git;
    return { success: false, error: git.error };
  }

  async getRepositoryDiff(owner, repo, branch, fromSha, toSha) {
    const repoPath = this.gitRepoService.getLocalRepoPath(owner, repo, branch);
    return await this.gitRepoService.getDiff(repoPath, fromSha || null, toSha || 'HEAD', { patch: true });
  }

  async getRepositoryChangesSince(owner, repo, branch, sinceSha) {
    const repoPath = this.gitRepoService.getLocalRepoPath(owner, repo, branch);
    return await this.gitRepoService.getChangedFilesSince(repoPath, sinceSha);
  }

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

module.exports = GiteaAdapter;


