package com.loremind.application.campaigncontext;

import com.loremind.domain.campaigncontext.Scene;
import com.loremind.domain.campaigncontext.ports.SceneRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * Service d'application pour le contexte Scene.
 * Orchestre la logique métier en utilisant le Port SceneRepository.
 * Fait partie de la couche Application de l'Architecture Hexagonale.
 */
@Service
public class SceneService {

    private final SceneRepository sceneRepository;

    public SceneService(SceneRepository sceneRepository) {
        this.sceneRepository = sceneRepository;
    }

    public Scene createScene(String name, String description, String chapterId, int order) {
        Scene scene = Scene.builder()
                .name(name)
                .description(description)
                .chapterId(chapterId)
                .order(order)
                .build();
        return sceneRepository.save(scene);
    }

    public Optional<Scene> getSceneById(String id) {
        return sceneRepository.findById(id);
    }

    public List<Scene> getAllScenes() {
        return sceneRepository.findAll();
    }

    public List<Scene> getScenesByChapterId(String chapterId) {
        return sceneRepository.findByChapterId(chapterId);
    }

    /**
     * Met à jour une Scene avec tous ses champs narratifs (Parameter Object pattern).
     */
    public Scene updateScene(String id, Scene updated) {
        Optional<Scene> existingScene = sceneRepository.findById(id);
        if (existingScene.isEmpty()) {
            throw new IllegalArgumentException("Scene non trouvée avec l'ID: " + id);
        }

        Scene scene = existingScene.get();
        scene.setName(updated.getName());
        scene.setDescription(updated.getDescription());
        scene.setOrder(updated.getOrder());
        scene.setLocation(updated.getLocation());
        scene.setTiming(updated.getTiming());
        scene.setAtmosphere(updated.getAtmosphere());
        scene.setPlayerNarration(updated.getPlayerNarration());
        scene.setGmSecretNotes(updated.getGmSecretNotes());
        scene.setChoicesConsequences(updated.getChoicesConsequences());
        scene.setCombatDifficulty(updated.getCombatDifficulty());
        scene.setEnemies(updated.getEnemies());
        scene.setRelatedPageIds(updated.getRelatedPageIds());
        return sceneRepository.save(scene);
    }

    public void deleteScene(String id) {
        sceneRepository.deleteById(id);
    }

    public boolean sceneExists(String id) {
        return sceneRepository.existsById(id);
    }
}
