import { useQuery } from "@tanstack/react-query";
import { apiGet } from "@/lib/api/client";

/** Backend sends int.MaxValue for "no limit". */
export const UNLIMITED = 2147483647;

export interface PlanLimits {
  maxOrdersPerDay: number;
  maxTables: number;
  maxTerminals: number;
  maxCustomers: number;
  maxSmsPerMonth: number;
  maxBranches: number;
  maxReportHistoryDays: number;
  maxMenuCategories: number;
  maxMenuItems: number;
  maxMenuAi3dPerMonth: number;
}

export interface PlatformPlan {
  tier: string;
  displayNameFa: string;
  displayNameEn?: string | null;
  monthlyPriceToman: number;
  isBillableOnline: boolean;
  isActive: boolean;
  sortOrder: number;
  limits: PlanLimits;
  featureKeys: string[];
}

export interface PlatformFeature {
  id: string;
  key: string;
  displayNameFa: string;
  displayNameEn?: string | null;
  moduleGroup: string;
  isEnabledGlobally: boolean;
}

/** Live, admin-editable plan matrix — the single source of truth for plan
 *  names, prices, limits, and included features. */
export function usePlatformPlans(cafeId?: string | null) {
  return useQuery({
    queryKey: ["platform-plans", cafeId],
    queryFn: async () => {
      const plans = await apiGet<PlatformPlan[]>(`/api/cafes/${cafeId}/platform/plans`);
      return plans
        .filter((p) => p.isActive)
        .sort((a, b) => a.sortOrder - b.sortOrder);
    },
    enabled: !!cafeId,
    staleTime: 5 * 60_000,
  });
}

export function usePlatformFeaturesCatalog(cafeId?: string | null) {
  return useQuery({
    queryKey: ["platform-features-catalog", cafeId],
    queryFn: () =>
      apiGet<PlatformFeature[]>(`/api/cafes/${cafeId}/platform/features-catalog`),
    enabled: !!cafeId,
    staleTime: 5 * 60_000,
  });
}

export function planDisplayName(plan: PlatformPlan, locale: string): string {
  if (locale === "en" && plan.displayNameEn) return plan.displayNameEn;
  return plan.displayNameFa;
}

export function featureDisplayName(feature: PlatformFeature, locale: string): string {
  if (locale === "en" && feature.displayNameEn) return feature.displayNameEn;
  return feature.displayNameFa;
}
