import { createCoreAPIClient } from "@/lib/features/coreClient";
import type { CoreResponse } from "@/lib/features/types";
import type { GuruAllowlistEntry, GuruTicket } from "./types";

const coreClient = createCoreAPIClient();
const BASE = "/v1/admin-console/guru";

export async function createTicket(input: {
  member_ref?: string;
  category?: string;
  summary?: string;
}): Promise<CoreResponse<{ ticket: GuruTicket }>> {
  return coreClient(`${BASE}/tickets`, {
    method: "POST",
    body: JSON.stringify(input),
  });
}

export async function startChatSession(
  reference: string,
): Promise<
  CoreResponse<{
    signed_url: string;
    reference: string;
    dynamic_variables?: Record<string, string>;
  }>
> {
  return coreClient(
    `${BASE}/tickets/${encodeURIComponent(reference)}/session`,
    { method: "POST" },
  );
}

export async function bindConversation(
  reference: string,
  conversationId: string,
): Promise<CoreResponse<{ bound: boolean; reopened: boolean }>> {
  return coreClient(
    `${BASE}/tickets/${encodeURIComponent(reference)}/conversations`,
    {
      method: "POST",
      body: JSON.stringify({ conversation_id: conversationId }),
    },
  );
}

export async function uploadAttachment(
  reference: string,
  file: File,
): Promise<CoreResponse<{ attached: boolean; title: string }>> {
  const form = new FormData();
  form.append("file", file);
  return coreClient(
    `${BASE}/tickets/${encodeURIComponent(reference)}/attachments`,
    { method: "POST", body: form },
  );
}

export async function closeTicket(
  reference: string,
): Promise<CoreResponse<{ closed: boolean }>> {
  return coreClient(`${BASE}/tickets/${encodeURIComponent(reference)}/close`, {
    method: "POST",
  });
}

export async function confirmGuruAction(
  actionId: string,
): Promise<CoreResponse<{ executed: boolean; one_time_password?: string }>> {
  return coreClient(`${BASE}/actions/${encodeURIComponent(actionId)}/confirm`, {
    method: "POST",
  });
}

export async function declineGuruAction(
  actionId: string,
): Promise<CoreResponse<{ declined: boolean }>> {
  return coreClient(`${BASE}/actions/${encodeURIComponent(actionId)}/decline`, {
    method: "POST",
  });
}

export async function addToAllowlist(
  email: string,
): Promise<CoreResponse<{ entry: GuruAllowlistEntry }>> {
  return coreClient(`${BASE}/allowlist`, {
    method: "POST",
    body: JSON.stringify({ email }),
  });
}

export async function removeFromAllowlist(
  email: string,
): Promise<CoreResponse<{ removed: boolean }>> {
  return coreClient(`${BASE}/allowlist`, {
    method: "DELETE",
    body: JSON.stringify({ email }),
  });
}
