package com.betriebsratkanzlei.legalconsenthub.form_element

import com.betriebsratkanzlei.legalconsenthub.error.FormElementSectionNotFoundException
import com.betriebsratkanzlei.legalconsenthub_api.model.CreateFormElementDto
import com.betriebsratkanzlei.legalconsenthub_api.model.FormElementDto
import org.springframework.stereotype.Component

@Component
class FormElementMapper(
    private val formOptionMapper: FormOptionMapper,
    private val formElementSectionRepository: FormElementSectionRepository
) {
    fun toFormElementDto(formElement: FormElement): FormElementDto {
        return FormElementDto(
            id = formElement.id ?: throw IllegalStateException("ApplicationForm ID must not be null!"),
            title = formElement.title,
            description = formElement.description,
            options = formElement.options.map { formOptionMapper.toFormOptionDto(it) },
            type = formElement.type,
            formElementSectionId = formElement.formElementSection?.id
                ?: throw IllegalStateException("FormElementSection ID must not be null!")
        )
    }

    fun toFormElement(formElement: FormElementDto): FormElement {
        val formElementSection = formElementSectionRepository.findById(formElement.formElementSectionId)
            .orElseThrow { FormElementSectionNotFoundException(formElement.formElementSectionId) }

        return FormElement(
            id = formElement.id,
            title = formElement.title,
            description = formElement.description,
            options = formElement.options.map { formOptionMapper.toFormOption(it) }.toMutableList(),
            type = formElement.type,
            formElementSection = formElementSection
        )
    }

    fun toFormElement(formElement: CreateFormElementDto, formElementSection: FormElementSection): FormElement {
        return FormElement(
            id = null,
            title = formElement.title,
            description = formElement.description,
            options = formElement.options.map { formOptionMapper.toFormOption(it) }.toMutableList(),
            type = formElement.type,
            formElementSection = formElementSection
        )
    }
}
