package com.ffii.fpsms.modules.common.mail.service

import com.ffii.fpsms.modules.common.mail.entity.MailTemplate
import com.ffii.fpsms.modules.common.mail.entity.MailTemplateRepository
import com.ffii.fpsms.modules.common.mail.web.models.MailTemplateRequest
import org.springframework.stereotype.Service

@Service
open class MailTemplateService(
    private val mailTemplateRepository: MailTemplateRepository,
) {
    fun allMailTemplates(): List<MailTemplate> {
        return mailTemplateRepository.findAllByDeletedIsFalse();
    }

    fun findById(id: Long): MailTemplate? {
        return mailTemplateRepository.findByIdAndDeletedIsFalse(id);
    }

    fun saveMailTemplate(request: MailTemplateRequest): MailTemplate {
        val mailTemplate = request.id?.let { findById(it) } ?: MailTemplate()

        mailTemplate.apply {
            to = request.to
            cc = request.cc
            code = request.code
            description = request.description
            type = request.type
            params = request.params
            subjectCht = request.subjectCht
            subjectEng = request.subjectEng
            contentCht = request.contentCht
            contentEng = request.contentEng
        }

        val response = mailTemplateRepository.saveAndFlush(mailTemplate)

        return response
    }

    fun saveMailTemplates(requests: List<MailTemplateRequest>) {
        val mailTemplates: List<MailTemplate> = mutableListOf()
        requests.forEach { request ->
            val mailTemplate = request.id?.let { findById(it) } ?: MailTemplate()

            mailTemplate.apply {
                to = request.to
                cc = request.cc
                code = request.code
                description = request.description
                type = request.type
                params = request.params
                subjectCht = request.subjectCht
                subjectEng = request.subjectEng
                contentCht = request.contentCht
                contentEng = request.contentEng
            }.let { mailTemplates.plus(it) }
        }

        mailTemplateRepository.saveAll(mailTemplates)
    }
}