import { createHash } from 'node:crypto'

function normalizeRecipe(recipe) {
  return {
    ...recipe,
    components: recipe.components.map((component) => ({
      ...component,
      owned: 0,
    })),
    canCraft: false,
  }
}

function normalizeDungeon(dungeon) {
  return {
    ...dungeon,
    completionCount: 0,
    leaderboard: [],
    leaderboards: {
      part_1: [],
      part_2: [],
      part_3: [],
      full_run: [],
    },
  }
}

export function normalizeCatalogProfile(profile) {
  return {
    ...profile,
    character: {
      ...profile.character,
      id: 1,
      name: 'Mira',
      level: 1,
      experience: 0,
      talentPoints: 1,
      currentLevelExperience: 0,
      nextLevelExperience: 100,
    },
    abilitySlots: profile.abilitySlots,
    allocatedTalentPoints: 0,
    inventory: [],
    completedDungeonParts: 0,
    completedRaidPhases: 0,
    gearStats: {
      averageItemLevel: 0,
      healingPower: 0,
      maxResourceBonus: 0,
    },
    setBonuses: profile.setBonuses.map((bonus) => ({
      ...bonus,
      equippedPieces: 0,
      active: false,
    })),
    craftingRecipes: profile.craftingRecipes.map(normalizeRecipe),
    dungeons: profile.dungeons.map(normalizeDungeon),
    hunterStats: {
      bossKills: {},
      bossPets: {},
      pvpMatchesPlayed: 0,
      pvpMatchesWon: 0,
    },
  }
}

export function catalogHash(profile) {
  return createHash('sha256')
    .update(JSON.stringify(profile))
    .digest('hex')
}

export function catalogPayload(profile) {
  const normalized = normalizeCatalogProfile(profile)
  return {
    version: 1,
    hash: catalogHash(normalized),
    profile: normalized,
  }
}
