package com.betriebsratkanzlei.legalconsenthub.form_element

import com.betriebsratkanzlei.legalconsenthub.application_form.ApplicationForm
import com.betriebsratkanzlei.legalconsenthub.application_form.ApplicationFormRepository
import com.betriebsratkanzlei.legalconsenthub.error.ApplicationFormNotFoundException
import com.betriebsratkanzlei.legalconsenthub_api.model.CreateFormElementSectionDto
import com.betriebsratkanzlei.legalconsenthub_api.model.FormElementSectionDto
import org.springframework.stereotype.Component

@Component
class FormElementSectionMapper(
    private val formElementMapper: FormElementMapper,
    private val applicationFormRepository: ApplicationFormRepository
) {
    fun toFormElementSectionDto(formElementSection: FormElementSection): FormElementSectionDto {
        return FormElementSectionDto(
            id = formElementSection.id ?: throw IllegalStateException("FormElementSection ID must not be null!"),
            title = formElementSection.title,
            description = formElementSection.description,
            shortTitle = formElementSection.shortTitle,
            formElements = formElementSection.formElements.map { formElementMapper.toFormElementDto(it) },
            applicationFormId =  formElementSection.applicationForm?.id
                ?: throw IllegalStateException("ApplicationForm ID must not be null!")
        )
    }

    fun toFormElementSection(formElementSection: FormElementSectionDto): FormElementSection {
        val applicationForm = applicationFormRepository.findById(formElementSection.applicationFormId)
            .orElseThrow { ApplicationFormNotFoundException(formElementSection.applicationFormId) }

        return FormElementSection(
            id = formElementSection.id,
            title = formElementSection.title,
            description = formElementSection.description,
            shortTitle = formElementSection.shortTitle,
            formElements = formElementSection.formElements.map { formElementMapper.toFormElement(it) }.toMutableList(),
            applicationForm = applicationForm
        )
    }

    fun toFormElementSection(createFormElementSection: CreateFormElementSectionDto, applicationForm: ApplicationForm): FormElementSection {
        val formElementSection = FormElementSection(
            title = createFormElementSection.title,
            description = createFormElementSection.description,
            shortTitle = createFormElementSection.shortTitle,
            applicationForm = applicationForm
        )
        formElementSection.formElements = createFormElementSection.formElements
            .map { formElementMapper.toFormElement(it, formElementSection) }
            .toMutableList()
        return formElementSection
    }
}
