import z from 'zod';
import { Tab } from './schemas';
import { EntityMap } from '@ngrx/signals/entities';

export function getTabHelper(
  tabId: number,
  entities: Record<number, Tab>,
): Tab | undefined {
  return entities[tabId];
}

export function getMetadataHelper<T extends z.ZodTypeAny>(
  tabId: number,
  key: string,
  schema: T,
  entities: EntityMap<Tab>,
): z.infer<T> | undefined {
  const metadata = getTabHelper(tabId, entities)?.metadata;

  if (!metadata) {
    return undefined;
  }

  const res = schema.safeParse(metadata?.[key]);
  if (res.success) {
    return res.data;
  }
  return undefined;
}

/**
 * Gets the next tab name for a Vorgang (process).
 *
 * @param entities - All tab entities
 * @returns Tab name in format "Vorgang X" where X is the count of existing Vorgang tabs + 1
 *
 * Behavior:
 * - Counts all tabs matching pattern "Vorgang \\d+"
 * - Returns "Vorgang {count + 1}"
 * - Example: If 2 Vorgang tabs exist -> returns "Vorgang 3"
 */
export function getNextTabNameHelper(entities: EntityMap<Tab>): string {
  const REGEX_PROCESS_NAME = /^Vorgang \d+$/;
  const allTabs = Object.values(entities);

  // Count tabs with "Vorgang X" pattern
  const vorgangTabCount = allTabs.filter((tab) =>
    REGEX_PROCESS_NAME.test(tab.name),
  ).length;

  return `Vorgang ${vorgangTabCount + 1}`;
}

// TODO: #5484 Move Logic to other location
/**
 * Formats the customer name for tab display.
 *
 * For B2B accounts (have 'b2b' feature and not 'staff' feature), shows organization name.
 * For regular customers, shows first and last name.
 * Falls back to organization name if personal names are missing.
 *
 * @param customer - The customer data
 * @returns Formatted customer name for display, or empty string if no name available
 */
export const formatCustomerTabNameHelper = (customer: {
  firstName?: string | null;
  lastName?: string | null;
  organisation?: { name?: string | null } | null;
  features?: Array<{ key?: string }> | null;
}): string => {
  // Format tab name with customer info (same logic as details-main-view)
  let name = `${customer.firstName ?? ''} ${customer.lastName ?? ''}`.trim();

  // Check if this is a B2B account (has 'b2b' feature and not 'staff' feature)
  const isBusinessKonto =
    !!customer.features?.some((f) => f.key === 'b2b') &&
    !customer.features?.some((f) => f.key === 'staff');

  // For B2B accounts or when names are missing, use organization name
  if (
    (isBusinessKonto && customer.organisation?.name) ||
    (!customer.firstName && !customer.lastName)
  ) {
    name = customer.organisation?.name ?? '';
  }

  return name;
};

// TODO: #5484 Move Logic to other location
/**
 * Helper function to check if a shopping cart has items.
 *
 * @param cart - The shopping cart object or null/undefined
 * @returns True if cart has items, false otherwise
 */
export const checkCartHasItemsHelper = (
  cart: { items?: unknown[] | null } | null | undefined,
): boolean => {
  return (cart?.items?.length ?? 0) > 0;
};
