import { createClient } from "@metagptx/web-sdk";

/**
 * Client-side helpers for the Knowledge Base article feedback widget.
 *
 * The backend stores ratings in the `kb_article_feedback` table on
 * Atoms Cloud. Public `/all` endpoint is used because KB feedback is
 * open to all visitors (including unauthenticated ones).
 */

export type FeedbackRating = "up" | "down";

export interface KbFeedbackPayload {
  article_id: string;
  category_id?: string;
  rating: FeedbackRating;
  comment?: string;
  user_email?: string;
  page_url?: string;
  user_agent?: string;
}

export interface KbFeedbackRecord {
  id: number;
  article_id: string;
  category_id?: string | null;
  rating: FeedbackRating;
  comment?: string | null;
  user_email?: string | null;
  page_url?: string | null;
  user_agent?: string | null;
  created_at?: string | null;
  updated_at?: string | null;
}

export interface KbFeedbackStats {
  up: number;
  down: number;
  total: number;
}

const client = createClient();

/**
 * Submit a feedback record for a KB article.
 * Returns the created record on success, or null on failure.
 */
export async function submitKbFeedback(
  payload: KbFeedbackPayload,
): Promise<KbFeedbackRecord | null> {
  try {
    const res = await client.apiCall.invoke({
      url: "/api/v1/entities/kb_article_feedback",
      method: "POST",
      data: {
        article_id: payload.article_id,
        category_id: payload.category_id ?? null,
        rating: payload.rating,
        comment: payload.comment?.trim() || null,
        user_email: payload.user_email?.trim() || null,
        page_url: payload.page_url ?? null,
        user_agent: payload.user_agent ?? null,
      },
    });
    const record = (res?.data ?? res) as KbFeedbackRecord | null;
    if (record && typeof record === "object" && "id" in record) {
      return record as KbFeedbackRecord;
    }
    return null;
  } catch (err) {
    // Surface in console for debugging but never break the UI.
    // eslint-disable-next-line no-console
    console.warn("[kbFeedback] submit failed", err);
    return null;
  }
}

/**
 * Fetch aggregated thumbs-up / thumbs-down counts for an article.
 * Uses the public `/all` endpoint and aggregates client-side.
 */
export async function fetchKbFeedbackStats(
  articleId: string,
): Promise<KbFeedbackStats> {
  const empty: KbFeedbackStats = { up: 0, down: 0, total: 0 };
  try {
    const res = await client.apiCall.invoke({
      url: "/api/v1/entities/kb_article_feedback/all",
      method: "GET",
      data: {
        query: JSON.stringify({ article_id: articleId }),
        limit: 2000,
      },
    });
    const items = (res?.data?.items ?? []) as Array<{ rating?: string }>;
    let up = 0;
    let down = 0;
    for (const it of items) {
      if (it?.rating === "up") up += 1;
      else if (it?.rating === "down") down += 1;
    }
    return { up, down, total: up + down };
  } catch {
    return empty;
  }
}

/**
 * Local-storage key used to remember whether the current browser
 * has already voted on an article, so we can hide the form or show
 * a "thanks" state and prevent trivial duplicate submissions.
 */
export function feedbackStorageKey(articleId: string): string {
  return `kb-feedback:${articleId}`;
}