import wagtail_factories
from django.conf import settings
from wagtail.models import Site

from vbv_lernwelt.course.consts import COURSE_VERSICHERUNGSVERMITTLERIN_ID
from vbv_lernwelt.course.factories import CoursePageFactory


def create_versicherungsvermittlerin_with_categories(
    apps=None,
    schema_editor=None,
    course_id=COURSE_VERSICHERUNGSVERMITTLERIN_ID,
    title="Versicherungsvermittler/-in",
):
    if apps is not None:
        Course = apps.get_model("course", "Course")
        CourseCategory = apps.get_model("course", "CourseCategory")
    else:
        # pylint: disable=import-outside-toplevel
        from vbv_lernwelt.course.models import Course, CourseCategory

    course, _ = Course.objects.get_or_create(
        id=course_id,
        title=title,
        category_name="Handlungsfeld",
    )

    CourseCategory.objects.get_or_create(course=course, title="Allgemein", general=True)

    for cat in [
        "Fahrzeug",
        "Reisen",
        "Einkommenssicherung",
        "Gesundheit",
        "Haushalt",
        "Sparen",
        "Pensionierung",
        "KMU",
        "Wohneigentum",
        "Rechtsstreitigkeiten",
        "Erben / Vererben",
        "Selbstständigkeit",
    ]:
        CourseCategory.objects.get_or_create(course=course, title=cat)

    # create default course page
    site = Site.objects.filter(is_default_site=True).first()
    if not site:
        site = wagtail_factories.SiteFactory(is_default_site=True)

    if settings.APP_ENVIRONMENT == "development":
        site.port = 8000
        site.save()

    course_page = CoursePageFactory(
        title=title,
        parent=site.root_page,
        course=course,
    )
    course.slug = course_page.slug
    course.save()

    return course
