import { env } from "@/lib/env";

/**
 * Minimal ClickUp API v2 client, shared by Kevo (task creation) and Guru
 * (tasks + comments; endpoints verified against developer.clickup.com,
 * createtaskcomment / gettaskcomments, Nov 2026).
 * Status sync-back is deliberately out of scope.
 */

export class ClickUpApiError extends Error {
  constructor(
    public status: number,
    public body: string,
  ) {
    super(`ClickUp API ${status}: ${body.slice(0, 300)}`);
    this.name = "ClickUpApiError";
  }
}

export interface ClickUpTask {
  id: string;
  url: string;
}

const clickUpFetch = async <T>(
  path: string,
  init: Omit<RequestInit, "body"> & { body?: unknown } = {},
): Promise<T> => {
  const token = env.GetString("CLICKUP_API_TOKEN");
  if (!token) throw new Error("CLICKUP_API_TOKEN is not set");
  const { body, ...rest } = init;
  const res = await fetch(`https://api.clickup.com/api/v2${path}`, {
    ...rest,
    headers: {
      Authorization: token,
      "Content-Type": "application/json",
    },
    ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
    signal: AbortSignal.timeout(15_000),
  });
  const text = await res.text();
  if (!res.ok) throw new ClickUpApiError(res.status, text);
  return (text ? JSON.parse(text) : undefined) as T;
};

/** Create a task. listId defaults to CLICKUP_LIST_ID (the Kevo list). */
export const createClickUpTask = async (task: {
  name: string;
  markdown_description: string;
  tags?: string[];
  listId?: string;
  assignees?: number[];
}): Promise<ClickUpTask> => {
  const listId = task.listId ?? env.GetString("CLICKUP_LIST_ID");
  if (!listId) throw new Error("CLICKUP_LIST_ID is not set");
  const json = await clickUpFetch<{ id: string; url: string }>(
    `/list/${listId}/task`,
    {
      method: "POST",
      body: {
        name: task.name,
        markdown_description: task.markdown_description,
        tags: task.tags ?? ["kevo"],
        ...(task.assignees?.length ? { assignees: task.assignees } : {}),
      },
    },
  );
  return { id: json.id, url: json.url };
};

export const createClickUpTaskComment = async (
  taskId: string,
  commentText: string,
): Promise<{ id: string }> =>
  clickUpFetch<{ id: string }>(`/task/${taskId}/comment`, {
    method: "POST",
    body: { comment_text: commentText, notify_all: false },
  });

export interface ClickUpComment {
  id: string;
  comment_text: string;
  user?: { username?: string; email?: string };
  date: string;
}

/** Newest-to-oldest, first page (25). Enough for reopen context. */
export const getClickUpTaskComments = async (
  taskId: string,
): Promise<ClickUpComment[]> => {
  const { comments } = await clickUpFetch<{ comments: ClickUpComment[] }>(
    `/task/${taskId}/comment`,
  );
  return comments;
};

/** Current task status + url (read-only sync back to Console 2). */
export const getClickUpTask = async (
  taskId: string,
): Promise<{ status: { status: string; type: string } | null; url: string }> => {
  const t = await clickUpFetch<{
    status?: { status: string; type: string };
    url: string;
  }>(`/task/${taskId}`);
  return { status: t.status ?? null, url: t.url };
};

/** Multipart upload (screenshots). Field name per API docs: "attachment". */
export const uploadClickUpTaskAttachment = async (
  taskId: string,
  file: { name: string; type: string; bytes: ArrayBuffer },
): Promise<{ id: string; title: string; url: string }> => {
  const token = env.GetString("CLICKUP_API_TOKEN");
  if (!token) throw new Error("CLICKUP_API_TOKEN is not set");
  const form = new FormData();
  form.append(
    "attachment",
    new Blob([file.bytes], { type: file.type }),
    file.name,
  );
  const res = await fetch(
    `https://api.clickup.com/api/v2/task/${taskId}/attachment`,
    {
      method: "POST",
      headers: { Authorization: token }, // no Content-Type: FormData sets it
      body: form,
      signal: AbortSignal.timeout(30_000),
    },
  );
  const text = await res.text();
  if (!res.ok) throw new ClickUpApiError(res.status, text);
  return JSON.parse(text) as { id: string; title: string; url: string };
};

/**
 * Close a task by moving it to the list's "closed"-type status (falls back
 * to a "done"-type one). List statuses are configurable per list, so they
 * are looked up rather than hardcoded.
 */
export const closeClickUpTask = async (
  taskId: string,
  listId: string,
): Promise<void> => {
  const { statuses } = await clickUpFetch<{
    statuses: Array<{ status: string; type: string }>;
  }>(`/list/${listId}`);
  const target =
    statuses.find((s) => s.type === "closed") ??
    statuses.find((s) => s.type === "done");
  if (!target)
    throw new ClickUpApiError(422, "List has no closed/done status");
  await clickUpFetch(`/task/${taskId}`, {
    method: "PUT",
    body: { status: target.status },
  });
};

export const addClickUpTaskTags = async (
  taskId: string,
  tags: string[],
): Promise<void> => {
  // Tag endpoints are per-tag: POST /task/{id}/tag/{tag_name}
  for (const tag of tags) {
    await clickUpFetch(`/task/${taskId}/tag/${encodeURIComponent(tag)}`, {
      method: "POST",
    });
  }
};
