package com.betriebsratkanzlei.legalconsenthub.application_form_template

import com.betriebsratkanzlei.legalconsenthub.application_form.ApplicationForm
import com.betriebsratkanzlei.legalconsenthub.application_form.ApplicationFormMapper
import com.betriebsratkanzlei.legalconsenthub.application_form.ApplicationFormRepository
import com.betriebsratkanzlei.legalconsenthub.error.ApplicationFormNotCreatedException
import com.betriebsratkanzlei.legalconsenthub.error.ApplicationFormNotDeletedException
import com.betriebsratkanzlei.legalconsenthub.error.ApplicationFormNotFoundException
import com.betriebsratkanzlei.legalconsenthub.error.ApplicationFormNotUpdatedException
import com.betriebsratkanzlei.legalconsenthub_api.model.ApplicationFormDto
import com.betriebsratkanzlei.legalconsenthub_api.model.CreateApplicationFormDto
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.stereotype.Service
import java.util.UUID

@Service
class ApplicationFormTemplateService(
    private val applicationFormRepository: ApplicationFormRepository,
    private val applicationFormMapper: ApplicationFormMapper
) {

    fun createApplicationFormTemplate(createApplicationFormDto: CreateApplicationFormDto): ApplicationForm {
        val applicationForm = applicationFormMapper.toApplicationForm(createApplicationFormDto)
        val savedApplicationForm: ApplicationForm
        try {
            savedApplicationForm = applicationFormRepository.save(applicationForm)
        } catch (e: Exception) {
            throw ApplicationFormNotCreatedException(e)
        }

        return savedApplicationForm
    }

    fun getApplicationFormTemplateById(id: UUID): ApplicationForm {
        return applicationFormRepository.findById(id).orElseThrow { ApplicationFormNotFoundException(id) }
    }

    fun getApplicationFormTemplates(): Page<ApplicationForm> {
        val pageable = PageRequest.of(0, 10)
        return applicationFormRepository.findAllByIsTemplateTrue(pageable)
    }

    fun updateApplicationFormTemplate(applicationFormDto: ApplicationFormDto): ApplicationForm {
        val applicationForm = applicationFormMapper.toApplicationForm(applicationFormDto)
        val updatedApplicationForm: ApplicationForm

        try {
            updatedApplicationForm = applicationFormRepository.save(applicationForm)
        } catch (e: Exception) {
            throw ApplicationFormNotUpdatedException(e, applicationFormDto.id)
        }

        return updatedApplicationForm
    }

    fun deleteApplicationFormTemplateByID(id: UUID) {
        try {
            applicationFormRepository.deleteById(id)
        } catch (e: Exception) {
            throw ApplicationFormNotDeletedException(e)
        }
    }
}
