import { Injectable, Logger } from '@nestjs/common';

const GITEA_BASE = 'https://git.admin.longde.cloud/api/v1';
const GITEA_TOKEN = process.env.GITEA_TOKEN || '0b190ab69b751c6f4ce3f92cbd3ed762e5cd5bfa';

@Injectable()
export class GiteaService {
  private readonly logger = new Logger(GiteaService.name);

  private async giteaGet<T>(path: string): Promise<T | null> {
    try {
      const res = await fetch(`${GITEA_BASE}${path}`, {
        headers: { Authorization: `token ${GITEA_TOKEN}`, Accept: 'application/json' },
      });
      if (!res.ok) { this.logger.warn(`Gitea GET ${path}: ${res.status}`); return null; }
      return await res.json() as T;
    } catch (err: any) {
      this.logger.warn(`Gitea GET ${path} failed: ${err.message}`);
      return null;
    }
  }

  private extractData<T>(response: any): T | null {
    if (!response) return null;
    // Gitea API wraps responses in {ok: true, data: ...}
    if (response.ok && Array.isArray(response.data)) return response.data as T;
    // Direct array response (standard REST API)
    if (Array.isArray(response)) return response as T;
    return null;
  }

  async getRepos() {
    let repos: any[] | null = null;

    const searchResult = await this.giteaGet<any>('/repos/search?q=&limit=50');
    repos = this.extractData<any[]>(searchResult);

    if (!repos || repos.length === 0) {
      const userResult = await this.giteaGet<any>('/user/repos?limit=50');
      repos = this.extractData<any[]>(userResult);
    }
    if (!repos) return [];

    const enriched: any[] = [];
    for (const r of repos) {
      const fullName = r.full_name;
      enriched.push({
        id: r.id, name: r.name, fullName, description: r.description,
        owner: r.owner?.login, stars: r.stars_count ?? 0, forks: r.forks_count ?? 0,
        openIssues: r.open_issues_count ?? 0, openPulls: 0, milestones: 0,
        defaultBranch: r.default_branch, updatedAt: r.updated_at,
      });
    }
    return enriched;
  }

  async getMilestones(owner: string, repo: string) {
    const result = await this.giteaGet<any>(`/repos/${owner}/${repo}/milestones?state=all`);
    return this.extractData<any[]>(result) ?? [];
  }

  async getIssues(owner: string, repo: string, milestone?: string, state = 'open') {
    let path = `/repos/${owner}/${repo}/issues?state=${state}&limit=50`;
    if (milestone) path += `&milestone=${milestone}`;
    const result = await this.giteaGet<any>(path);
    return this.extractData<any[]>(result) ?? [];
  }

  async getRunners() {
    const result = await this.giteaGet<any>('/admin/runners');
    return this.extractData<any[]>(result) ?? [];
  }

  async getReleases(owner: string, repo: string) {
    const result = await this.giteaGet<any>(`/repos/${owner}/${repo}/releases?limit=20`);
    return this.extractData<any[]>(result) ?? [];
  }
}
