package dev.inmo.postssystem.features.content.text.server

import com.benasher44.uuid.uuid4
import dev.inmo.micro_utils.repos.exposed.AbstractExposedCRUDRepo
import dev.inmo.micro_utils.repos.exposed.initTable
import dev.inmo.postssystem.features.content.common.ContentId
import dev.inmo.postssystem.features.content.common.RegisteredContent
import dev.inmo.postssystem.features.content.server.storage.ServerContentStorage
import dev.inmo.postssystem.features.content.text.common.TextContent
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.statements.InsertStatement
import org.jetbrains.exposed.sql.statements.UpdateStatement

class TextServerContentStorage(
    override val database: Database
) : ServerContentStorage<TextContent>,
    AbstractExposedCRUDRepo<RegisteredContent, ContentId, TextContent>(tableName = "TextContent") {

    val idColumn = text("id")
    private val textColumn = text("text")

    override val selectByIds: SqlExpressionBuilder.(List<ContentId>) -> Op<Boolean> = {
        idColumn.inList(it.map { it.string })
    }
    override val selectById: SqlExpressionBuilder.(ContentId) -> Op<Boolean> = {
        idColumn.eq(it.string)
    }
    override val ResultRow.asObject: RegisteredContent
        get() = RegisteredContent(
            ContentId(get(idColumn)),
            TextContent(get(textColumn))
        )

    init {
        initTable()
    }

    override fun insert(value: TextContent, it: InsertStatement<Number>) {
        it[idColumn] = uuid4().toString()
        it[textColumn] = value.text
    }

    override fun update(id: ContentId, value: TextContent, it: UpdateStatement) {
        it[textColumn] = value.text
    }

    override fun InsertStatement<Number>.asObject(value: TextContent): RegisteredContent {
        return RegisteredContent(
            ContentId(get(idColumn)),
            TextContent(get(textColumn))
        )
    }
}
