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

const FILE_NAME = "task.ts";

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

export interface AttioTaskInput extends Pick<AttioTask, "deadline_at" | "is_completed" | "linked_records" | "assignees" | "created_at"> {
  content: string;
  format: "plaintext" | "markdown";
}

export interface AttioTaskQueryParams {
  limit?: number;
  offset?: number;
  sort?: "created_at:asc" | "created_at:desc";
  linked_object?: string;
  linked_record_id?: string;
  assignee?: string | null;
  is_completed?: boolean | null;
}

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

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

  async getAll(query: AttioTaskQueryParams = {}): Promise<AttioTask[]> {
    return this.extractData(
      this.client.doFetch(this.createBaseUrl(), {
        method: "GET",
        query,
      })
    );
  }

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

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

  async update(id: string, data: Partial<AttioTaskInput>): Promise<AttioTask> {
    return this.extractData(
      this.client.doFetch(\`$\{this.createBaseUrl()}/$\{id}\`, {
        method: "PUT",
        body: data,
      })
    );
  }

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

  ${generateWebhookEventFunctionForList({
    eventNames: ["task.created", "task.updated", "task.deleted"],
    idKey: "task_id",
    populatedType: "AttioTask",
  })}
}`;

  writeGeneratedFile(outputDir, FILE_NAME, content);
}
