import { writeGeneratedFile } from "../../helpers/fs";
import { generateFileHeader } from "../types/fileHeader";

const FILE_NAME = "base.ts";

export function generateBaseFetcher(outputDir: string): void {
  const content = `${generateFileHeader(FILE_NAME)}
import { Response } from "node-fetch";
import { AttioClient } from "../attioClient";

export class HTTPResponseError extends Error {
  public readonly status: number;
  public readonly statusText: string;

  constructor(
    public readonly response: Response,
    public readonly body: any = null
  ) {
    super(\`HTTP Error Response: $\{response.status} $\{response.statusText}\`);
    this.status = response.status;
    this.statusText = response.statusText;
  }

  static async create(response: Response): Promise<HTTPResponseError> {
    const body: any = await response.json().catch(() => response.text()).catch(() => null);
    return new HTTPResponseError(response, body);
  }
}

export abstract class BaseFetcher {
  constructor(protected readonly client: AttioClient) {}

  protected abstract createBaseUrl(...args: any[]): string;

  protected async extractData<R>(responsePromise: Promise<Response>): Promise<R> {
    const response = await responsePromise;
    if (response.ok) {
      return (await response.json() as { data: R; }).data as R;
    }

    throw await HTTPResponseError.create(response);
  }
}
`;

  writeGeneratedFile(outputDir, FILE_NAME, content);
}
