import type { PrismaClient } from '@prisma/client';
import { DEFAULT_MARKET_TYPES, buildMarketTemplate } from '@thebet365/shared';

/** 为演示赛事补齐详情页玩法（与后台 markets 模板一致） */
export async function seedDemoMarkets(prisma: PrismaClient, matchId: bigint) {
  const configs = DEFAULT_MARKET_TYPES.map((marketType) => ({
    marketType,
    ...buildMarketTemplate(marketType),
  }));

  for (const cfg of configs) {
    const exists = await prisma.market.findFirst({
      where: { matchId, marketType: cfg.marketType },
      include: { _count: { select: { selections: true } } },
    });
    if (exists) {
      const needRefresh =
        cfg.marketType.includes('CORRECT_SCORE') &&
        exists._count.selections < cfg.selectionTemplate.length;
      if (needRefresh) {
        const existing = await prisma.marketSelection.findMany({
          where: { marketId: exists.id },
          select: { selectionCode: true },
        });
        const existingCodes = new Set(existing.map((s) => s.selectionCode));
        const missing = cfg.selectionTemplate
          .map((s, i) => ({ ...s, sortOrder: i }))
          .filter((s) => !existingCodes.has(s.code));
        if (missing.length > 0) {
          await prisma.marketSelection.createMany({
            data: missing.map((s) => ({
              marketId: exists.id,
              selectionCode: s.code,
              selectionName: s.name,
              odds: s.odds,
              sortOrder: s.sortOrder,
              status: 'OPEN',
            })),
          });
        }
      }
      continue;
    }
    await prisma.market.create({
      data: {
        matchId,
        marketType: cfg.marketType,
        period: cfg.period,
        lineValue: cfg.defaultLineValue,
        allowSingle: cfg.allowSingle,
        allowParlay: cfg.allowParlay,
        sortOrder: cfg.sortOrder,
        status: 'OPEN',
        selections: {
          create: cfg.selectionTemplate.map((s, i) => ({
            selectionCode: s.code,
            selectionName: s.name,
            odds: s.odds,
            sortOrder: i,
            status: 'OPEN',
          })),
        },
      },
    });
  }
}
