import { writeGeneratedFile } from "../../helpers/fs";
import { generateFileHeader } from "../types/fileHeader";
import { generateWebhookEventFunction, generateWebhookEventFunctionForList } from "../webhookEventFactory";

const FILE_NAME = "note.ts";

export function generateNoteFetcher(outputDir: string): void {
  const content = `${generateFileHeader(FILE_NAME)}
import { AttioClient } from "./attioClient";
import { BaseFetcher } from "./base";
import { AttioWebhookEventPopulatedListener } from "./webhook";
import { AttioNote, WebhookEventDataByType } from "../types";

export interface AttioNoteQueryParams {
  limit?: number;
  offset?: number;
  parent_object?: string;
  parent_record_id?: string;
}
 
export interface AttioNoteInput extends Pick<AttioNote, "parent_object" | "parent_record_id" | "title" | "created_at"> {
  content: string;
  format: "plaintext" | "markdown";
}

export class AttioNoteFetcher extends BaseFetcher {
  constructor(client: AttioClient) {
    super(client);
  }

  protected createBaseUrl(): string {
    return "/notes";
  }

  async getAll(query: AttioNoteQueryParams = {}): Promise<AttioNote[]> {
    return this.extractData(
      this.client.doFetch(this.createBaseUrl(), {
        query,
      })
    );
  }

  async create(data: AttioNoteInput): Promise<AttioNote> {
    return this.extractData(
      this.client.doFetch(this.createBaseUrl(), {
        method: "POST",
        body: data,
      })
    );
  }

  async getById(id: string): Promise<AttioNote> {
    return this.extractData(
      this.client.doFetch(\`$\{this.createBaseUrl()}/$\{id}\`)
    );
  }

  async delete(id: string): Promise<void> {
    await this.client.doFetch(\`$\{this.createBaseUrl()}/$\{id}\`, {
      method: "DELETE",
    });
  }

  ${generateWebhookEventFunctionForList({
    eventNames: ["note.created", "note.updated", "note.deleted"],
    idKey: "note_id",
    populatedType: "AttioNote",
  })}

  ${generateWebhookEventFunction({
    eventName: "note-content.updated",
    customPrefix: "onContent",
    idKey: "note_id",
    populatedType: "AttioNote",
  })}
}`;

  writeGeneratedFile(outputDir, FILE_NAME, content);
}
