package com.ffii.fpsms.modules.jobOrder.service

import com.ffii.fpsms.modules.jobOrder.web.model.CreateJobOrderRequest
import com.ffii.fpsms.modules.master.web.models.MessageResponse
import com.ffii.fpsms.modules.productProcess.service.ProductProcessService
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
open class JobOrderCreationService(
    private val jobOrderService: JobOrderService,
    private val jobOrderBomMaterialService: JobOrderBomMaterialService,
    private val jobOrderProcessService: JobOrderProcessService,
    private val productProcessService: ProductProcessService,
) {
    /**
     * 建立 JO 並完成所有關聯資料（BOM materials / processes / productprocess + lines）。
     * 任一步失敗會整體回滾，避免留下「JO 有、productprocess 沒有」的半成品。
     */
    @Transactional(rollbackFor = [Exception::class])
    open fun createJobOrderWithFullFlow(request: CreateJobOrderRequest, productionPriority: Int?): MessageResponse {
        val jo = jobOrderService.createJobOrder(request)
        val joId = jo.id ?: throw IllegalStateException("Job Order creation failed: returned object ID is null.")

        jobOrderBomMaterialService.createJobOrderBomMaterialsByJoId(joId)
        jobOrderProcessService.createJobOrderProcessesByJoId(joId)
        productProcessService.createProductProcessByJobOrderId(joId, productionPriority)

        return jo
    }
}

