package dp.kotul.jwtapi.repository

import dp.kotul.jwt.model.User
import org.slf4j.Logger
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.stereotype.Repository
import java.sql.ResultSet

interface InstancesRepository {
    fun getUserBySession(sessionId: String, instanceId: Int): User?
}

@Repository
class InstancesRepositoryImpl(val jdbcTemplate: NamedParameterJdbcTemplate, val log: Logger) : InstancesRepository {

    override fun getUserBySession(sessionId: String, instanceId: Int): User? {
        log.info("Validating login with session $sessionId and instance $instanceId")

        return getResult(
            "SELECT ui.sen_id, ui.id AS inst_id, u.com_id, u.usr_id , u.lae_id " +
                    "FROM usr_instance ui " +
                    "   JOIN usr_user u ON ui.usr_id = u.id " +
                    "   JOIN usr_company c ON ui.com_id = c.id " +
                    "WHERE ui.sen_id = :session_id " +
                    "   AND ui.id = :instance_id ",
            mapOf("session_id" to sessionId, "instance_id" to instanceId)
        )
    }

    private fun getResult(query: String, paramMap: Map<String, Any>): User? {
        val instances: List<User> = jdbcTemplate.query(query, paramMap)
        { rs: ResultSet, _: Int ->
            User(
                sessionId = rs.getString("sen_id"),
                instanceId = rs.getInt("inst_id"),
                comId = rs.getInt("com_id"),
                usrId = rs.getInt("usr_id"),
                laeId = rs.getInt("lae_id")
            )
        }
        if (instances.isNotEmpty()) {
            log.info("Valid combination, userId: {}", instances[0].usrId)
        } else {
            log.info("Invalid combination")
        }
        return instances.firstOrNull()
    }
}
