import { Repository } from 'typeorm';
import { PlayerQuestArc } from '../quest/player-quest-arc.entity';
import { QuestArc } from '../quest/quest-arc.entity';

// Zone unlock chain: each zone requires completing the previous zone's arc
// marais → always open
// egouts → requires "Les Marais du Têtard" arc completed
// desert → requires the egouts arc completed
const ZONE_ORDER = ['marais', 'egouts', 'desert'];

export async function getUnlockedZones(
  characterId: string,
  arcRepo: Repository<QuestArc>,
  playerArcRepo: Repository<PlayerQuestArc>,
): Promise<string[]> {
  const unlocked: string[] = ['marais']; // always accessible

  // Get all completed arcs for this character
  const completedArcs = await playerArcRepo.find({
    where: { characterId, completed: true },
    relations: ['questArc'],
  });
  const completedArcZones = new Set(completedArcs.map(pa => pa.questArc?.zone).filter(Boolean));

  // Check zone chain: each zone unlocks the next
  for (let i = 0; i < ZONE_ORDER.length - 1; i++) {
    const currentZone = ZONE_ORDER[i];
    const nextZone = ZONE_ORDER[i + 1];

    // Find arc for current zone
    const arc = await arcRepo.findOne({ where: { zone: currentZone } });
    if (!arc) continue;

    // If this zone's arc is completed, unlock the next zone
    const isCompleted = completedArcs.some(pa => pa.questArcId === arc.id);
    if (isCompleted) {
      unlocked.push(nextZone);
    } else {
      break; // Can't skip zones
    }
  }

  return unlocked;
}
