export interface GitHubCommit {
  sha: string;
  message: string;
  author: string;
  date: string;
  url: string;
}

export interface GitHubPR {
  number: number;
  title: string;
  state: 'open' | 'closed';
  author: string;
  createdAt: string;
  url: string;
}

export class GitHubClient {
  private readonly base = 'https://api.github.com';

  constructor(
    private readonly repo: string,
    private readonly token?: string,
  ) {}

  private headers(): Record<string, string> {
    const h: Record<string, string> = {
      Accept: 'application/vnd.github+json',
      'X-GitHub-Api-Version': '2022-11-28',
    };
    if (this.token) h['Authorization'] = `Bearer ${this.token}`;
    return h;
  }

  private async request<T>(path: string): Promise<T> {
    const res = await fetch(`${this.base}${path}`, { headers: this.headers() });
    if (!res.ok) {
      throw new Error(`GitHub API ${res.status}: ${res.statusText}`);
    }
    return res.json() as Promise<T>;
  }

  async getRecentCommits(count = 15): Promise<GitHubCommit[]> {
    const data = await this.request<
      Array<{
        sha: string;
        commit: { message: string; author: { name: string; date: string } };
        html_url: string;
      }>
    >(`/repos/${this.repo}/commits?per_page=${count}`);

    return data.map((c) => ({
      sha: c.sha.slice(0, 7),
      message: c.commit.message.split('\n')[0]!, // first line only
      author: c.commit.author.name,
      date: c.commit.author.date,
      url: c.html_url,
    }));
  }

  async getRecentPRs(count = 10): Promise<GitHubPR[]> {
    const data = await this.request<
      Array<{
        number: number;
        title: string;
        state: string;
        user: { login: string };
        created_at: string;
        html_url: string;
      }>
    >(`/repos/${this.repo}/pulls?state=all&per_page=${count}&sort=created&direction=desc`);

    return data.map((pr) => ({
      number: pr.number,
      title: pr.title,
      state: pr.state as 'open' | 'closed',
      author: pr.user.login,
      createdAt: pr.created_at,
      url: pr.html_url,
    }));
  }
}
