import { Injectable } from '@nestjs/common';
import type { Perk, PerkModifier, Survivor } from '@fog-explorer/api-interfaces';

export interface SynergyModifier extends PerkModifier {
  sourceKey: string;
}

@Injectable()
export class GroupSynergyService {
  /**
   * Collect every perk modifier from all active survivors in a SWF group,
   * deduplicating by perkKey so one survivor's perk doesn't stack with itself
   * if they appear multiple times.
   */
  collectGroupModifiers(survivors: Survivor[]): SynergyModifier[] {
    const seen = new Set<string>();
    const modifiers: SynergyModifier[] = [];

    for (const survivor of survivors) {
      if (survivor.state === 'sacrificed') continue;

      for (const perk of survivor.perkSlots) {
        const dedupKey = `${survivor.id}:${perk.key}`;
        if (seen.has(dedupKey)) continue;
        seen.add(dedupKey);

        for (const mod of perk.modifiers) {
          modifiers.push({ ...mod, sourceKey: perk.key });
        }
      }
    }

    return modifiers;
  }

  /**
   * Build an augmented perk list for a specific survivor that includes
   * group-wide synergy perks from other survivors as phantom perk entries.
   * Only `successChance` modifiers propagate group-wide; stat modifiers stay personal.
   */
  buildAugmentedPerks(
    targetSurvivor: Survivor,
    groupModifiers: SynergyModifier[]
  ): Perk[] {
    const personal = targetSurvivor.perkSlots;
    const personalKeys = new Set(personal.map((p) => p.key));

    const synergies = groupModifiers
      .filter((m) => m.target === 'successChance' && !personalKeys.has(m.sourceKey))
      .map(
        (m): Perk => ({
          id: '00000000-0000-4000-a000-000000000000',
          key: `synergy:${m.sourceKey}`,
          name: `Group: ${m.sourceKey}`,
          description: '',
          tags: [],
          modifiers: [{ target: m.target, type: m.type, amount: m.amount, condition: m.condition }],
        })
      );

    return [...personal, ...synergies];
  }
}
