package com.betriebsratkanzlei.legalconsenthub.application_form_version

import com.betriebsratkanzlei.legalconsenthub.user.UserMapper
import com.betriebsratkanzlei.legalconsenthub_api.model.ApplicationFormSnapshotDto
import com.betriebsratkanzlei.legalconsenthub_api.model.ApplicationFormVersionDto
import com.betriebsratkanzlei.legalconsenthub_api.model.ApplicationFormVersionListItemDto
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.stereotype.Component

@Component
class ApplicationFormVersionMapper(
    private val userMapper: UserMapper,
    private val objectMapper: ObjectMapper,
) {
    fun toApplicationFormVersionDto(version: ApplicationFormVersion): ApplicationFormVersionDto {
        val snapshot = objectMapper.readValue(version.snapshotData, ApplicationFormSnapshotDto::class.java)

        return ApplicationFormVersionDto(
            id = version.id ?: throw IllegalStateException("ApplicationFormVersion ID must not be null!"),
            applicationFormId =
                version.applicationForm.id
                    ?: throw IllegalStateException("ApplicationForm ID must not be null!"),
            versionNumber = version.versionNumber,
            name = version.name,
            status = version.status,
            organizationId = version.organizationId,
            snapshot = snapshot,
            createdBy = userMapper.toUserDto(version.createdBy),
            createdAt =
                version.createdAt
                    ?: throw IllegalStateException("ApplicationFormVersion createdAt must not be null!"),
        )
    }

    fun toApplicationFormVersionListItemDto(version: ApplicationFormVersion): ApplicationFormVersionListItemDto =
        ApplicationFormVersionListItemDto(
            id = version.id ?: throw IllegalStateException("ApplicationFormVersion ID must not be null!"),
            applicationFormId =
                version.applicationForm.id
                    ?: throw IllegalStateException("ApplicationForm ID must not be null!"),
            versionNumber = version.versionNumber,
            name = version.name,
            status = version.status,
            organizationId = version.organizationId,
            createdBy = userMapper.toUserDto(version.createdBy),
            createdAt =
                version.createdAt
                    ?: throw IllegalStateException("ApplicationFormVersion createdAt must not be null!"),
        )
}

