import { MetabaseDashboard } from "../services/api/metabaseService";

/**
 * Utility functions for Metabase dashboard management
 */

/**
 * Find dashboard by metabase dashboard number
 */
export const findDashboardByNumber = (
  dashboards: MetabaseDashboard[],
  dashboardNumber: number
): MetabaseDashboard | undefined => {
  return dashboards.find((d) => d.metabaseDashboardNumber === dashboardNumber);
};

/**
 * Display-only labels for permitted Metabase dashboards.
 */
export const formatDashboardDisplayName = (name: string): string => {
  if (!name?.trim()) return name;

  return name
    .replace(/position\s+performance/gi, "Team Leader Performance")
    .replace(/employee\s+performance/gi, "Expert Performance")
    .replace(/^position$/i, "Team Leader")
    .replace(/^employee$/i, "Expert");
};

export const getFormattedDashboardLabel = (
  name: string | { en?: string; am?: string } | undefined,
  locale: "en" | "am" = "en",
): string => {
  if (!name) return "Dashboard";

  const raw =
    typeof name === "string"
      ? name
      : (locale === "am" ? name.am : name.en) || name.en || name.am || "Dashboard";

  return formatDashboardDisplayName(raw);
};

/**
 * Get dashboard display name (prefers English, falls back to Amharic)
 */
export const getDashboardDisplayName = (
  dashboard: MetabaseDashboard,
): string => {
  const raw =
    dashboard.name.en ||
    dashboard.name.am ||
    `Dashboard #${dashboard.metabaseDashboardNumber}`;

  return formatDashboardDisplayName(raw);
};

/**
 * Get dashboard description (prefers English, falls back to Amharic)
 */
export const getDashboardDescription = (
  dashboard: MetabaseDashboard
): string => {
  return dashboard.description.en || dashboard.description.am || "";
};

/**
 * Check if dashboard has parameters
 */
export const hasParameters = (dashboard: MetabaseDashboard): boolean => {
  return dashboard.params && dashboard.params.length > 0;
};

/**
 * Sort dashboards by dashboard number
 */
export const sortDashboardsByNumber = (
  dashboards: MetabaseDashboard[]
): MetabaseDashboard[] => {
  return [...dashboards].sort(
    (a, b) => a.metabaseDashboardNumber - b.metabaseDashboardNumber
  );
};

/**
 * Filter dashboards by tenant ID
 */
export const filterDashboardsByTenant = (
  dashboards: MetabaseDashboard[],
  tenantId: string
): MetabaseDashboard[] => {
  return dashboards.filter((d) => d.tenantId === tenantId);
};
