import { DEFAULT_STORE_CONFIG } from './default-store-config';

/**
 * Forma de configuración que consume `novasis-ecommerce-store`.
 * Coincide 1:1 con el tipo `StoreConfig` de la tienda.
 */
export type StoreConfig = Record<string, unknown>;

/**
 * Construye el objeto `StoreConfig` plano que espera la tienda a partir de las
 * columnas y JSONB de `ecommerce_config`. Si un bloque viene vacío, usa el
 * diseño estándar (DEFAULT_STORE_CONFIG) como fallback.
 */
export function buildStoreConfig(
  row: {
    subdominio?: string | null;
    nombre_comercial?: string | null;
    slogan?: string | null;
    logo_url?: string | null;
    favicon_url?: string | null;
    estado?: string | null;
    theme_config?: any;
    layout_config?: any;
    catalog_config?: any;
    promotion_slots?: any;
    seasonal_templates?: any;
    checkout_config?: any;
    notifications_config?: any;
    footer_config?: any;
    content_pages_config?: any;
  },
  opts: { status: 'draft' | 'published' | 'default' | 'closed' } = { status: 'published' },
): StoreConfig {
  const def = DEFAULT_STORE_CONFIG as any;
  const theme = row.theme_config ?? {};
  const layout = row.layout_config ?? {};
  const catalog = row.catalog_config ?? {};

  return {
    version: 1,
    status: opts.status,
    source: 'tenant',
    identity: {
      name: row.nombre_comercial ?? def.identity.name,
      slogan: row.slogan ?? def.identity.slogan,
      subdomain: row.subdominio ?? def.identity.subdomain,
      logoText: theme.logoText ?? (row.nombre_comercial ?? def.identity.name).charAt(0).toUpperCase(),
      logoUrl: row.logo_url ?? null,
      faviconUrl: row.favicon_url ?? null,
    },
    theme: { ...def.theme, ...(theme.theme ?? theme.colors ?? {}) },
    typography: { ...def.typography, ...(theme.typography ?? {}) },
    catalog: { ...def.catalog, ...catalog },
    search: { ...def.search, ...(layout.search ?? {}) },
    promotions: { ...def.promotions, ...(row.promotion_slots ?? {}) },
    texts: { ...def.texts, ...(layout.texts ?? {}) },
    footer: normalizeFooterConfig(row.footer_config, def.footer),
    contentPages: isEmpty(row.content_pages_config) ? def.contentPages : row.content_pages_config,
    checkout: { ...def.checkout, ...(row.checkout_config ?? {}) },
    notifications: { ...def.notifications, ...(row.notifications_config ?? {}) },
    layout: { ...def.layout, ...(layout.layout ?? layout) },
    // Sin temporadas propias, la tienda no tiene temporadas. Antes caía en las de ejemplo
    // de la plantilla ("Primavera fresca", frutas y bebidas) y la temporada activa pisaba
    // la barra superior y el banner del comercio, mientras el panel decía "No hay
    // temporadas configuradas" y no había cómo apagarlas.
    seasons: Array.isArray(row.seasonal_templates) ? row.seasonal_templates : [],
  };
}

/**
 * Configuración estándar de fallback (cuando una empresa todavía no tiene
 * ninguna versión publicada). Devuelve el diseño base tal cual.
 */
export function defaultStoreConfig(subdominio?: string): StoreConfig {
  return {
    ...(DEFAULT_STORE_CONFIG as any),
    status: 'default',
    source: 'fallback',
    identity: {
      ...(DEFAULT_STORE_CONFIG as any).identity,
      ...(subdominio ? { subdomain: subdominio } : {}),
    },
  };
}

function isEmpty(v: any): boolean {
  if (v == null) return true;
  if (Array.isArray(v)) return v.length === 0;
  if (typeof v === 'object') return Object.keys(v).length === 0;
  return false;
}

function normalizeFooterConfig(value: any, fallback: any): any {
  const footer = value && typeof value === 'object' && !Array.isArray(value) ? value : {};
  const contact = footer.contact && typeof footer.contact === 'object' ? footer.contact : {};
  const map = contact.map && typeof contact.map === 'object' ? contact.map : {};

  return {
    ...fallback,
    ...footer,
    labels: { ...(fallback.labels ?? {}), ...(footer.labels ?? {}) },
    contact: {
      ...(fallback.contact ?? {}),
      ...contact,
      map: { ...(fallback.contact?.map ?? {}), ...map },
    },
    linkGroups: Array.isArray(footer.linkGroups) ? footer.linkGroups : fallback.linkGroups,
    paymentMethods: Array.isArray(footer.paymentMethods) ? footer.paymentMethods : fallback.paymentMethods,
    socialLinks: Array.isArray(footer.socialLinks) ? footer.socialLinks : fallback.socialLinks,
  };
}
