package com.ffii.fpsms.modules.stock.service

import com.ffii.fpsms.modules.stock.entity.ItemLotTraceLog
import com.ffii.fpsms.modules.stock.entity.ItemLotTraceLogRepository
import com.ffii.fpsms.modules.user.entity.User
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Isolation
import org.springframework.transaction.annotation.Transactional

@Service
open class ItemLotTraceLogService(
    private val itemLotTraceLogRepository: ItemLotTraceLogRepository,
) {
    private val log = LoggerFactory.getLogger(javaClass)

    @Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = [Exception::class], readOnly = false)
    open fun insert(
        user: User,
        inventoryLotId: Long?,
        lotNo: String?,
        itemId: Long?,
        itemCode: String?,
    ) {
        val entity = ItemLotTraceLog().apply {
            this.userId = user.id
            this.username = user.username
            this.inventoryLotId = inventoryLotId
            this.lotNo = lotNo?.takeIf { it.isNotBlank() }
            this.itemId = itemId
            this.itemCode = itemCode?.takeIf { it.isNotBlank() }
        }
        itemLotTraceLogRepository.save(entity)
    }

    /** Best-effort audit write; never fails the main trace. */
    open fun insertQuietly(
        user: User?,
        inventoryLotId: Long?,
        lotNo: String?,
        itemId: Long?,
        itemCode: String?,
    ) {
        if (user?.id == null) {
            log.warn("Skip item_lot_trace_log insert: no authenticated user")
            return
        }
        try {
            insert(
                user = user,
                inventoryLotId = inventoryLotId,
                lotNo = lotNo,
                itemId = itemId,
                itemCode = itemCode,
            )
        } catch (e: Exception) {
            log.warn("Failed to insert item_lot_trace_log: {}", e.message, e)
        }
    }
}
