/**
 * Configurable product list (generic-platform support): the NEXT_PUBLIC_PRODUCTS
 * override parser must be defensive so a bad env value can never blank the switcher.
 */

import { describe, it, expect } from 'vitest';
import { parseProductsEnv, DEFAULT_PRODUCTS, type Product } from '@/lib/product-constants';

const fallback: readonly Product[] = [{ id: 'only', name: 'Only' }];

describe('parseProductsEnv', () => {
  it('returns the fallback for empty / missing input', () => {
    expect(parseProductsEnv(undefined, fallback)).toBe(fallback);
    expect(parseProductsEnv('', fallback)).toBe(fallback);
    expect(parseProductsEnv('   ', fallback)).toBe(fallback);
  });

  it('parses a valid JSON array of products', () => {
    const raw = JSON.stringify([
      { id: 'acme', name: 'Acme App', icon: 'Box' },
      { id: 'beta', name: 'Beta' },
    ]);
    expect(parseProductsEnv(raw, fallback)).toEqual([
      { id: 'acme', name: 'Acme App', icon: 'Box' },
      { id: 'beta', name: 'Beta' },
    ]);
  });

  it('defaults a missing name to the id and drops the icon when absent', () => {
    expect(parseProductsEnv(JSON.stringify([{ id: 'x' }]), fallback)).toEqual([
      { id: 'x', name: 'x' },
    ]);
  });

  it('skips malformed entries but keeps valid ones', () => {
    const raw = JSON.stringify([{ id: '' }, null, 42, { name: 'no id' }, { id: 'ok', name: 'OK' }]);
    expect(parseProductsEnv(raw, fallback)).toEqual([{ id: 'ok', name: 'OK' }]);
  });

  it('falls back on non-array JSON, invalid JSON, or an all-invalid array', () => {
    expect(parseProductsEnv('{"id":"x"}', fallback)).toBe(fallback); // object, not array
    expect(parseProductsEnv('not json', fallback)).toBe(fallback);
    expect(parseProductsEnv(JSON.stringify([{ bad: true }]), fallback)).toBe(fallback);
  });

  it('the built-in default is non-empty with unique ids', () => {
    expect(DEFAULT_PRODUCTS.length).toBeGreaterThan(0);
    const ids = DEFAULT_PRODUCTS.map(p => p.id);
    expect(new Set(ids).size).toBe(ids.length);
  });
});
