package org.fuseri.moduleexercise.question;

import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.fuseri.moduleexercise.answer.Answer;
import org.fuseri.moduleexercise.common.DomainObject;
import org.fuseri.moduleexercise.exercise.Exercise;

import java.util.HashSet;
import java.util.Set;

/**
 * Represent Question entity
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@Table(name = "question")
public class Question extends DomainObject {

    private String text;

    @OneToMany(mappedBy = "question", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<Answer> answers = new HashSet<>();

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "exercise_id", nullable = false)
    private Exercise exercise;

    /**
     * Add answers to question
     *
     * @param answersToAdd to add
     */
    public void addAnswers(Set<Answer> answersToAdd) {
        answers.addAll(answersToAdd);
        for (var answer : answersToAdd) {
            answer.setQuestion(this);
        }
    }
}
