package com.nisemoe.nise.database

import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Service
import javax.sql.DataSource

data class ReplayCacheReplay(
    val replayId: Long,
    val mapId: Int,
    val userId: Int,
    val replayData: ByteArray,
    val mods: Int,
)

@Service
class ReplayCacheService(
    @Qualifier("replayCacheDataSource") private val dataSource: DataSource,
) {
    fun getReplayById(replayId: Long): ByteArray? =
        dataSource.connection.use { connection ->
            val statement = connection.prepareStatement("SELECT replay_data FROM replays WHERE replay_id = ?")
            statement.setLong(1, replayId)
            val resultSet = statement.executeQuery()

            var replayData: ByteArray? = null
            while (resultSet.next()) {
                replayData = resultSet.getBytes(1)
            }

            return replayData
        }

    fun insertReplay(replay: ReplayCacheReplay): Boolean =
        dataSource.connection.use { connection ->
            val statement = connection.prepareStatement("INSERT INTO replays VALUES (?, ?, ?, ?, ?)")
            statement.setLong(1, replay.replayId)
            statement.setInt(2, replay.mapId)
            statement.setInt(3, replay.userId)
            statement.setBytes(4, replay.replayData)
            statement.setInt(5, replay.mods)

            val updateCount = statement.executeUpdate()

            return updateCount != 0
        }
}
