# This file is part of Indico.
# Copyright (C) 2002 - 2026 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.

from indico.modules.events.cloning import get_attrs_to_clone
from indico.modules.events.surveys.clone import EventSurveyCloner
from indico.modules.events.surveys.models.items import SurveyItem, SurveyQuestion, SurveySection, SurveyText
from indico.modules.events.surveys.models.surveys import Survey


def test_survey_clone(db, create_event, dummy_event):
    survey = Survey(event=dummy_event, title='test')

    first_section = SurveySection(title='section 1', display_as_section=True, position=2)
    survey.items.append(first_section)
    first_section.children.append(SurveyQuestion(title='question in s1', field_type='text', is_required=True))

    second_section = SurveySection(title='section 2', display_as_section=True, position=1)
    survey.items.append(second_section)
    second_section.children.append(SurveyText(description='My text'))
    second_section.children.append(SurveyQuestion(title='What is your name?', field_type='text', is_required=False))

    db.session.flush()

    new_event = create_event()
    cloner = EventSurveyCloner(dummy_event)
    cloner.run(new_event, {}, {}, False)

    assert len(new_event.surveys) == 1
    assert len(new_event.surveys[0].items) == len(survey.items)
    for i, section in enumerate(new_event.surveys[0].sections):
        for attr in get_attrs_to_clone(SurveyItem):
            assert getattr(section, attr) == getattr(survey.sections[i], attr)
        for j, child in enumerate(section.children):
            for attr in get_attrs_to_clone(SurveyItem):
                assert getattr(child, attr) == getattr(survey.sections[i].children[j], attr)
