import { createCoreAPIClient } from "@/lib/features/coreClient";
import type { CoreResponse } from "@/lib/features/types";
import type {
  KevoFlag,
  KevoFlagCategory,
  KevoFlagStatus,
  KevoKnowledgeEntry,
} from "./types";

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

export async function updateFlag(
  reference: string,
  payload: { status?: KevoFlagStatus; reviewer_notes?: string },
): Promise<CoreResponse<KevoFlag>> {
  return coreClient(`${BASE}/flags/${reference}`, {
    method: "PATCH",
    body: JSON.stringify(payload),
  });
}

export async function createManualFlag(payload: {
  category: KevoFlagCategory;
  member_question: string;
  agent_answer?: string;
  member_claim?: string;
  entity?: string;
  requested_change?: string;
  conversation_id: string;
  member_id?: string;
}): Promise<CoreResponse<{ flag: KevoFlag; created: boolean }>> {
  return coreClient(`${BASE}/flags/manual`, {
    method: "POST",
    body: JSON.stringify(payload),
  });
}

export async function routeFlagToClickUp(
  reference: string,
): Promise<CoreResponse<KevoFlag>> {
  return coreClient(`${BASE}/flags/${reference}/clickup`, { method: "POST" });
}

export interface KnowledgePayload {
  flag_id?: string;
  entity: string;
  aliases: string[];
  property?: string;
  category: string;
  verified_text: string;
}

export async function createKnowledge(
  payload: KnowledgePayload,
): Promise<CoreResponse<KevoKnowledgeEntry>> {
  return coreClient(`${BASE}/knowledge`, {
    method: "POST",
    body: JSON.stringify(payload),
  });
}

export async function updateKnowledge(
  id: string,
  payload: Partial<KnowledgePayload>,
): Promise<CoreResponse<KevoKnowledgeEntry>> {
  return coreClient(`${BASE}/knowledge/${id}`, {
    method: "PATCH",
    body: JSON.stringify(payload),
  });
}

export async function approveKnowledge(
  id: string,
): Promise<CoreResponse<KevoKnowledgeEntry>> {
  return coreClient(`${BASE}/knowledge/${id}/approve`, { method: "POST" });
}

export async function retireKnowledge(
  id: string,
): Promise<CoreResponse<KevoKnowledgeEntry>> {
  return coreClient(`${BASE}/knowledge/${id}/retire`, { method: "POST" });
}

export async function publishKnowledge(): Promise<
  CoreResponse<{ skipped: boolean; hash: string; entries_count: number }>
> {
  return coreClient(`${BASE}/publish`, { method: "POST" });
}
