/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2026 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.sql

import de.steamwar.sql.internal.useDb
import org.jetbrains.exposed.v1.core.and
import org.jetbrains.exposed.v1.core.dao.id.EntityID
import org.jetbrains.exposed.v1.core.dao.id.IntIdTable
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.dao.IntEntity
import org.jetbrains.exposed.v1.dao.IntEntityClass

object ScriptTable : IntIdTable("Script") {
    val userId = reference("UserId", SteamwarUserTable).index()
    val name = varchar("Name", 64)
    val code = text("Code")

    init {
        uniqueIndex(userId, name)
    }
}

class Script(id: EntityID<Int>) : IntEntity(id) {
    companion object : IntEntityClass<Script>(ScriptTable) {
        @JvmStatic
        fun byId(id: Int) =
            useDb { findById(id) }

        @JvmStatic
        fun get(user: SteamwarUser, name: String) =
            useDb {
                find { ScriptTable.userId eq user.id and (ScriptTable.name eq name) }.firstOrNull()
            }

        @JvmStatic
        fun create(user: SteamwarUser, name: String, code: String) =
            useDb {
                new {
                    this.userId = user.id.value
                    this.scriptName = name
                    this.scriptCode = code
                }
            }

        @JvmStatic
        fun list(user: SteamwarUser) =
            useDb {
                find { ScriptTable.userId eq user.id }.toList()
            }
    }

    fun getId() =
        id.value

    var userId by ScriptTable.userId.transform({ EntityID(it, SteamwarUserTable) }, { it.value })
    private var scriptName by ScriptTable.name
    private var scriptCode by ScriptTable.code

    var name: String
        get() = scriptName
        set(value) = useDb { scriptName = value }

    var code: String
        get() = scriptCode
        set(value) = useDb { scriptCode = value }

    override fun delete() =
        useDb { super.delete() }
}