import { prisma } from './db.js';

/** Default categories seeded on boot / sync. */
export const ITEM_CATEGORIES = [
  'Rifle',
  'Pistol',
  'SMG',
  'Heavy',
  'Sniper',
  'Knife',
  'Gloves',
  'Sticker',
  'Agent',
  'Misc',
];

export function normalizeCategory(value) {
  const cat = String(value ?? '').trim();
  return cat || 'Misc';
}

/** Ensure a single category row exists; returns normalized name. */
export async function ensureCategory(name) {
  const normalized = normalizeCategory(name);
  await prisma.category.upsert({
    where: { name: normalized },
    create: { name: normalized },
    update: {},
  });
  return normalized;
}

/**
 * Seed defaults + any category strings already used on items.
 */
export async function ensureCategories() {
  const fromItems = await prisma.item.findMany({
    select: { category: true },
    distinct: ['category'],
  });
  const names = [
    ...new Set([
      ...ITEM_CATEGORIES,
      ...fromItems.map((r) => normalizeCategory(r.category)),
    ]),
  ];
  for (const name of names) {
    await prisma.category.upsert({
      where: { name },
      create: { name },
      update: {},
    });
  }
}

export async function listCategoriesWithCounts() {
  const [categories, grouped] = await Promise.all([
    prisma.category.findMany({ orderBy: { name: 'asc' } }),
    prisma.item.groupBy({
      by: ['category'],
      _count: { _all: true },
    }),
  ]);
  const countMap = new Map(grouped.map((g) => [g.category, g._count._all]));
  return categories.map((c) => ({
    id: c.id,
    name: c.name,
    itemCount: countMap.get(c.name) || 0,
    createdAt: c.createdAt,
  }));
}
