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

export type Plan = {
  id: number;
  service_type: string;
  name: string;
  price: number;
  currency?: string;
  billing_cycle?: string;
  features?: string;
  cta_label?: string;
  cta_url?: string;
  is_featured?: boolean;
  is_active?: boolean;
  sort_order?: number;
  tagline?: string;
};

const client = createClient();

export function parsePlanFeatures(raw?: string): string[] {
  if (!raw) return [];
  try {
    const parsed = JSON.parse(raw);
    return Array.isArray(parsed) ? parsed.map(String) : [];
  } catch {
    return String(raw)
      .split(/\r?\n|,/)
      .map((s) => s.trim())
      .filter(Boolean);
  }
}

/**
 * Fetch active plans for a given service type, sorted by sort_order.
 * Uses the /all endpoint because plans are public (create_only=false).
 */
export async function fetchPlansByService(serviceType: string): Promise<Plan[]> {
  try {
    const res = await client.apiCall.invoke({
      url: "/api/v1/entities/plans/all",
      method: "GET",
      data: {
        query: JSON.stringify({ service_type: serviceType, is_active: true }),
        sort: "sort_order",
        limit: 100,
      },
    });
    const items = (res?.data?.items ?? []) as Plan[];
    return items
      .filter((p) => p.is_active !== false)
      .sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0));
  } catch {
    return [];
  }
}