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

const FILE_NAME = "comment.ts";

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

export type AttioCommentInput = Pick<AttioComment, "author" | "thread_id" | "created_at"> & {
  content: string;
  format: "plaintext";
} & (
  | { entry: { entry_id: string; list_id: string } }
  | { record: { object_id: string; record_id: string } }
  | {}
);

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

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

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

  async getById(id: string): Promise<AttioComment> {
    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: ["comment.created", "comment.deleted", "comment.resolved", "comment.unresolved"],
    idKey: "comment_id",
    populatedType: "AttioComment",
  })}
}
`;

  writeGeneratedFile(outputDir, FILE_NAME, content);
}
