export type Product = {
  id: string;
  name: string;
  category: string;
  price: number;
  stock: number;
  color: string;
  shape: string;
  description: string;
};
export const products: Product[] = [
  {
    id: 'vase',
    name: 'Ваза Contour',
    category: 'Керамика',
    price: 480000,
    stock: 8,
    color: '#b89178',
    shape: 'vase',
    description:
      'Выразительный силуэт для одной ветки или большого пространства. Учебный товар.',
  },
  {
    id: 'cup',
    name: 'Чашка Everyday',
    category: 'Керамика',
    price: 240000,
    stock: 15,
    color: '#a7b8ae',
    shape: 'mug',
    description:
      'Предмет повседневного ритуала. Матовая поверхность, округлая ручка. Учебный товар.',
  },
  {
    id: 'ring',
    name: 'Кольцо Orbit',
    category: 'Аксессуары',
    price: 720000,
    stock: 4,
    color: '#c2a46f',
    shape: 'ring',
    description: 'Скульптурное кольцо и один гранёный акцент. Учебный товар.',
  },
  {
    id: 'speaker',
    name: 'Колонка Frequency',
    category: 'Техника',
    price: 1890000,
    stock: 6,
    color: '#8e999b',
    shape: 'speaker',
    description:
      'Компактная акустика с выразительной геометрией. Учебный товар.',
  },
  {
    id: 'chair',
    name: 'Стул Frame',
    category: 'Мебель',
    price: 2450000,
    stock: 3,
    color: '#c4b69d',
    shape: 'chair',
    description: 'Чёткая конструкция для спокойного интерьера. Учебный товар.',
  },
  {
    id: 'bottle',
    name: 'Флакон Essence',
    category: 'Аксессуары',
    price: 360000,
    stock: 12,
    color: '#b6a9c4',
    shape: 'bottle',
    description: 'Многоразовый флакон с рифлёной крышкой. Учебный товар.',
  },
];
export type CartLine = { id: string; quantity: number };
export function validCart(value: unknown): CartLine[] {
  if (!Array.isArray(value)) return [];
  const result = new Map<string, number>();
  for (const line of value) {
    if (
      line &&
      typeof line.id === 'string' &&
      products.some((p) => p.id === line.id) &&
      Number.isInteger(line.quantity) &&
      line.quantity > 0
    )
      result.set(
        line.id,
        Math.min(20, (result.get(line.id) || 0) + line.quantity),
      );
  }
  return [...result].map(([id, quantity]) => ({ id, quantity }));
}
export function cartTotal(lines: CartLine[]) {
  return lines.reduce(
    (sum, l) =>
      sum + (products.find((p) => p.id === l.id)?.price || 0) * l.quantity,
    0,
  );
}
export function filterProducts({
  q = '',
  category = 'all',
  sort = 'featured',
}: {
  q?: string;
  category?: string;
  sort?: string;
}) {
  const items = products.filter(
    (p) =>
      (category === 'all' || p.category === category) &&
      `${p.name} ${p.category}`
        .toLocaleLowerCase('ru')
        .includes(q.toLocaleLowerCase('ru')),
  );
  if (sort === 'price-asc') items.sort((a, b) => a.price - b.price);
  if (sort === 'price-desc') items.sort((a, b) => b.price - a.price);
  return items;
}
export const money = (minor: number) =>
  new Intl.NumberFormat('ru-RU', {
    style: 'currency',
    currency: 'RUB',
    maximumFractionDigits: 0,
  }).format(minor / 100);
export function quoteCart(input: unknown) {
  if (
    !input ||
    typeof input !== 'object' ||
    !('items' in input) ||
    !Array.isArray(input.items) ||
    input.items.length < 1 ||
    input.items.length > 20
  )
    throw new Error('Нужен массив items: от 1 до 20 позиций.');
  const map = new Map<string, number>();
  for (const line of input.items) {
    if (
      !line ||
      typeof line.id !== 'string' ||
      !Number.isInteger(line.quantity) ||
      line.quantity < 1 ||
      line.quantity > 20
    )
      throw new Error(
        'Каждая позиция содержит id и целое quantity от 1 до 20.',
      );
    if (!products.some((p) => p.id === line.id))
      throw new Error('Неизвестный товар.');
    map.set(line.id, (map.get(line.id) || 0) + line.quantity);
  }
  const items = [...map].map(([id, quantity]) => {
    const p = products.find((p) => p.id === id)!;
    if (quantity > p.stock)
      throw new Error(
        `Недостаточно на складе: ${p.name}. Доступно: ${p.stock}.`,
      );
    return { id, quantity, unitPrice: p.price, lineTotal: p.price * quantity };
  });
  return {
    currency: 'RUB',
    items,
    total: items.reduce((s, l) => s + l.lineTotal, 0),
    demo: true,
    message: 'Учебный расчёт. Заказ и платёж не создаются.',
  };
}
