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

/**
 * Client helpers for the Service Catalog testimonials feature.
 *
 * Records are stored in the `service_testimonials` table on Atoms Cloud
 * and managed from the CMS admin page. Public `/all` endpoint is used
 * so unauthenticated visitors can see the carousel.
 */

export interface ServiceTestimonial {
  id: number;
  name: string;
  company: string;
  role?: string | null;
  quote: string;
  rating: number;
  avatar_url?: string | null;
  display_order?: number | null;
  is_active?: boolean | null;
  created_at?: string | null;
  updated_at?: string | null;
}

export type TestimonialInput = Omit<
  ServiceTestimonial,
  "id" | "created_at" | "updated_at"
>;

const client = createClient();
const ENTITY_URL = "/api/v1/entities/service_testimonials";

export async function fetchPublicTestimonials(): Promise<ServiceTestimonial[]> {
  try {
    const res = await client.apiCall.invoke({
      url: `${ENTITY_URL}/all`,
      method: "GET",
      data: { limit: 200 },
    });
    const items = (res?.data?.items ?? []) as ServiceTestimonial[];
    return items
      .filter((t) => t && t.is_active !== false)
      .sort(
        (a, b) => (a.display_order ?? 999) - (b.display_order ?? 999),
      );
  } catch (err) {
    // eslint-disable-next-line no-console
    console.warn("[testimonials] fetch failed", err);
    return [];
  }
}

export async function fetchAllTestimonials(): Promise<ServiceTestimonial[]> {
  try {
    const res = await client.apiCall.invoke({
      url: `${ENTITY_URL}/all`,
      method: "GET",
      data: { limit: 500 },
    });
    const items = (res?.data?.items ?? []) as ServiceTestimonial[];
    return items.sort(
      (a, b) => (a.display_order ?? 999) - (b.display_order ?? 999),
    );
  } catch (err) {
    // eslint-disable-next-line no-console
    console.warn("[testimonials] fetch all failed", err);
    return [];
  }
}

export async function createTestimonial(
  payload: TestimonialInput,
): Promise<ServiceTestimonial | null> {
  try {
    const res = await client.apiCall.invoke({
      url: ENTITY_URL,
      method: "POST",
      data: payload,
    });
    return (res?.data ?? res) as ServiceTestimonial;
  } catch (err) {
    // eslint-disable-next-line no-console
    console.warn("[testimonials] create failed", err);
    return null;
  }
}

export async function updateTestimonial(
  id: number,
  payload: Partial<TestimonialInput>,
): Promise<ServiceTestimonial | null> {
  try {
    const res = await client.apiCall.invoke({
      url: `${ENTITY_URL}/${id}`,
      method: "PUT",
      data: payload,
    });
    return (res?.data ?? res) as ServiceTestimonial;
  } catch (err) {
    // eslint-disable-next-line no-console
    console.warn("[testimonials] update failed", err);
    return null;
  }
}

export async function deleteTestimonial(id: number): Promise<boolean> {
  try {
    await client.apiCall.invoke({
      url: `${ENTITY_URL}/${id}`,
      method: "DELETE",
    });
    return true;
  } catch (err) {
    // eslint-disable-next-line no-console
    console.warn("[testimonials] delete failed", err);
    return false;
  }
}