package de.walamana.models

import de.walamana.plugins.dbQuery
import kotlinx.serialization.Serializable
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.transactions.transaction

@Serializable
data class Mark(
    val mid: Int,
    val gid: Int,
    val value: Int
)

object Marks : Table() {
    val mid = integer("mid")
        .references(Ministranten.id, onDelete = ReferenceOption.CASCADE);
    val gid = integer("gid")
        .references(Gottesdienste.id, onDelete = ReferenceOption.CASCADE);
    val value = integer("value");

    override val primaryKey = PrimaryKey(mid, gid)
}

object MarksDao {

    private fun resultRowToMark(row: ResultRow) = Mark(
        row[Marks.mid],
        row[Marks.gid],
        row[Marks.value]
    )

    suspend fun allMarksForPlan(planId: Int): List<Mark> = dbQuery {
        Gottesdienste.join(Marks, JoinType.INNER, onColumn = Marks.gid, otherColumn = Gottesdienste.id)
            .select { Gottesdienste.planId eq planId }
            .map(::resultRowToMark)
    }

    suspend fun setMark(ministrantId: Int, gottesdienstId: Int, value: Int): Boolean = dbQuery {
        Marks.upsert {
            it[Marks.mid] = ministrantId
            it[Marks.gid] = gottesdienstId
            it[Marks.value] = value
        }.resultedValues?.isNotEmpty() ?: false
    }

    suspend fun removeMark(ministrantId: Int, gottesdienstId: Int): Boolean = dbQuery {
        Marks.deleteWhere {
            (Marks.gid eq gottesdienstId) and
                    (Marks.mid eq ministrantId)
        } > 0
    }

}
