from vbv_lernwelt.core.utils import get_django_content_type
from vbv_lernwelt.course.models import CourseCompletion, CourseCompletionStatus


def mark_course_completion(
    page, user, course_session, completion_status=CourseCompletionStatus.SUCCESS.value
):
    if completion_status not in CourseCompletionStatus.__members__:
        raise ValueError(
            f"Invalid value for CourseCompletionStatus: {completion_status}"
        )

    if not (
        hasattr(page.specific, "has_course_completion_status")
        and page.specific.has_course_completion_status
    ):
        return ValueError(
            f"Page {page.id} of type {get_django_content_type(page)}"
            f" cannot be marked as completed"
        )

    cc, created = CourseCompletion.objects.get_or_create(
        user_id=user.id,
        page_id=page.id,
        course_session_id=course_session.id,
    )
    cc.completion_status = completion_status
    cc.page_type = get_django_content_type(page.specific)

    cc.save()
    return cc
