import { Injectable, Logger } from '@nestjs/common';
import {
  IntegrationProvider,
  IntegrationDefinition,
  LinkDescription,
  OAuthConfig,
  ProviderAccount,
  PublicUnfurlOpts,
  ResolveAccountOpts,
  UnfurlPattern,
  UnfurlOpts,
  UnfurlResult,
} from '../../registry/integration-provider.interface';
import { GitHubService } from './github.service';
import { buildGitHubPatterns } from './github-patterns';
import { normalizeBaseUrl } from '../../utils/integration.utils';
import { credentialEnvKey } from '../../oauth/credential-env';

const DEFAULT_BASE_URL = 'https://github.com';

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

  definition: IntegrationDefinition = {
    type: 'github',
    name: 'GitHub',
    description: 'Link previews for repos, pull requests, issues, commits, and files',
    icon: 'github',
    capabilities: ['oauth', 'unfurl'],
    oauth: {
      authUrl: 'https://github.com/login/oauth/authorize',
      tokenUrl: 'https://github.com/login/oauth/access_token',
      scopes: ['repo', 'read:user'],
    },
  };

  constructor(private readonly githubService: GitHubService) {
    super();
    const configured = process.env.INTEGRATION_GITHUB_URL;
    if (configured && !normalizeBaseUrl(configured)) {
      this.logger.warn(
        `INTEGRATION_GITHUB_URL is not a valid http(s) URL; falling back to ${DEFAULT_BASE_URL}`,
      );
    }
  }

  getOAuthConfig(settings: Record<string, any>): OAuthConfig {
    const baseUrl = this.resolveBaseUrl();
    return {
      authUrl: `${baseUrl}/login/oauth/authorize`,
      tokenUrl: `${baseUrl}/login/oauth/access_token`,
      scopes: ['repo', 'read:user'],
    };
  }

  // Configured host only, so a GitHub Enterprise token never reaches github.com.
  getUnfurlPatterns(settings: Record<string, any>): UnfurlPattern[] {
    return buildGitHubPatterns(this.resolveBaseUrl());
  }

  getUnfurlHosts(settings: Record<string, any>): string[] {
    return [new URL(this.resolveBaseUrl()).hostname];
  }

  async resolveAccount(opts: ResolveAccountOpts): Promise<ProviderAccount> {
    return this.githubService.getAccount(
      `Bearer ${opts.accessToken}`,
      this.resolveApiBaseUrl(),
    );
  }

  async unfurl(opts: UnfurlOpts): Promise<UnfurlResult> {
    return this.unfurlWith(`Bearer ${opts.accessToken}`, opts);
  }

  // The OAuth app's own credentials only see public repos, so private ones 404.
  async unfurlPublic(opts: PublicUnfurlOpts): Promise<UnfurlResult> {
    const clientId =
      process.env[credentialEnvKey('CLIENT_ID', this.definition.type)];
    const clientSecret =
      process.env[credentialEnvKey('CLIENT_SECRET', this.definition.type)];
    if (!clientId || !clientSecret) {
      throw new Error('GitHub client ID or secret is not set');
    }
    const credentials = Buffer.from(`${clientId}:${clientSecret}`).toString(
      'base64',
    );
    return this.unfurlWith(`Basic ${credentials}`, opts);
  }

  private async unfurlWith(
    authorization: string,
    opts: PublicUnfurlOpts,
  ): Promise<UnfurlResult> {
    const { match, patternType, url } = opts;
    const apiBaseUrl = this.resolveApiBaseUrl();
    const owner = match[1];
    const repo = match[2];

    switch (patternType) {
      case 'github-pr': {
        const number = parseInt(match[3], 10);
        return this.githubService.unfurlPullRequest(
          authorization, apiBaseUrl, owner, repo, number, url,
        );
      }

      case 'github-issue': {
        const number = parseInt(match[3], 10);
        return this.githubService.unfurlIssue(
          authorization, apiBaseUrl, owner, repo, number, url,
        );
      }

      case 'github-repo':
        return this.githubService.unfurlRepo(
          authorization, apiBaseUrl, owner, repo, url,
        );

      case 'github-commit': {
        const sha = match[3];
        return this.githubService.unfurlCommit(
          authorization, apiBaseUrl, owner, repo, sha, url,
        );
      }

      case 'github-pr-commit': {
        const sha = match[4];
        return this.githubService.unfurlCommit(
          authorization, apiBaseUrl, owner, repo, sha, url,
        );
      }

      case 'github-file': {
        const ref = match[3];
        const path = match[4];
        const startLine = match[5] ? parseInt(match[5], 10) : undefined;
        const endLine = match[6] ? parseInt(match[6], 10) : undefined;
        return this.githubService.unfurlFile(
          owner, repo, ref, path, startLine, endLine, url,
        );
      }

      case 'github-pulls-list':
      case 'github-issues-list':
      case 'github-releases-list':
        return this.githubService.unfurlCollectionPage(
          authorization, apiBaseUrl, owner, repo, patternType.replace('github-', ''), url,
        );

      default:
        throw new Error(`Unknown GitHub pattern type: ${patternType}`);
    }
  }

  describeLink(
    patternType: string,
    match: RegExpMatchArray,
  ): LinkDescription | null {
    const repo = `${match[1]}/${match[2]}`;
    switch (patternType) {
      case 'github-pr':
        return { title: `Pull Request #${match[3]}`, description: repo };
      case 'github-pr-commit':
        return { title: `Commit ${match[4].slice(0, 7)}`, description: repo };
      case 'github-issue':
        return { title: `Issue #${match[3]}`, description: repo };
      case 'github-commit':
        return { title: `Commit ${match[3].slice(0, 7)}`, description: repo };
      case 'github-file':
        return { title: match[4], description: repo };
      case 'github-pulls-list':
        return { title: 'Pull Requests', description: repo };
      case 'github-issues-list':
        return { title: 'Issues', description: repo };
      case 'github-releases-list':
        return { title: 'Releases', description: repo };
      case 'github-repo':
        return { title: repo };
      default:
        return null;
    }
  }

  private resolveBaseUrl(): string {
    const baseUrl = process.env.INTEGRATION_GITHUB_URL;
    return (baseUrl && normalizeBaseUrl(baseUrl)) || DEFAULT_BASE_URL;
  }

  private resolveApiBaseUrl(): string {
    const baseUrl = this.resolveBaseUrl();
    return baseUrl === DEFAULT_BASE_URL
      ? 'https://api.github.com'
      : `${baseUrl}/api/v3`;
  }
}
