/*
 *   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.*
import org.jetbrains.exposed.v1.core.dao.id.CompositeID
import org.jetbrains.exposed.v1.core.dao.id.CompositeIdTable
import org.jetbrains.exposed.v1.core.dao.id.EntityID
import org.jetbrains.exposed.v1.dao.CompositeEntity
import org.jetbrains.exposed.v1.dao.CompositeEntityClass
import org.jetbrains.exposed.v1.javatime.timestamp
import org.jetbrains.exposed.v1.jdbc.insertIgnore
import java.sql.Timestamp

object CheckedSchematicTable : CompositeIdTable("CheckedSchematic") {
    val nodeId = optReference("NodeId", SchematicNodeTable, onDelete = ReferenceOption.SET_NULL, onUpdate = ReferenceOption.SET_NULL).index()
    val nodeOwner = reference("NodeOwner", SteamwarUserTable).index()
    val nodeName = varchar("NodeName", 64).entityId().index()
    val validator = reference("Validator", SteamwarUserTable).index()
    val startTime = timestamp("StartTime").entityId().index()
    val endTime = timestamp("EndTime")
    val declineReason = text("DeclineReason")
    val seen = bool("Seen").index()
    val nodeType = varchar("NodeType", 16)

    init {
        addIdColumn(nodeOwner)
        addIdColumn(nodeName)

        index(false, nodeOwner, endTime)
        index(false, startTime, endTime, nodeName)
        index(false, seen, nodeOwner, startTime)
    }
}

class CheckedSchematic(id: EntityID<CompositeID>) : CompositeEntity(id) {
    companion object : CompositeEntityClass<CheckedSchematic>(CheckedSchematicTable) {
        @JvmStatic
        fun create(node: SchematicNode, validator: Int, startTime: Timestamp, endTime: Timestamp, reason: String, seen: Boolean) =
            useDb {
                CheckedSchematicTable.insertIgnore {
                    it[this.nodeId] = node.id
                    it[this.nodeOwner] = EntityID(node.owner, SteamwarUserTable)
                    it[this.nodeName] = node.name
                    it[this.validator] = EntityID(validator, SteamwarUserTable)
                    it[this.startTime] = startTime.toInstant()
                    it[this.endTime] = endTime.toInstant()
                    it[this.declineReason] = reason
                    it[this.seen] = seen
                    it[this.nodeType] = node.schemtype.toDB().substring(1)
                }
            }

        @JvmStatic
        fun getLastDeclinedOfNode(node: Int) =
            useDb {
                find { (CheckedSchematicTable.nodeId eq node) and (CheckedSchematicTable.declineReason neq "Prüfvorgang abgebrochen") }.orderBy(CheckedSchematicTable.endTime to SortOrder.DESC).toList()
            }

        @JvmStatic
        fun previousChecks(node: SchematicNode) =
            useDb {
                find { (CheckedSchematicTable.nodeId eq node.id) and (CheckedSchematicTable.declineReason neq "") and (CheckedSchematicTable.declineReason neq "Prüfvorgang abgebrochen") }.orderBy(CheckedSchematicTable.endTime to SortOrder.DESC).toList()
            }

        @JvmStatic
        fun getUnseen(owner: SteamwarUser) =
            useDb {
                find { (CheckedSchematicTable.nodeOwner eq owner.id) and (CheckedSchematicTable.seen eq false) }.orderBy(CheckedSchematicTable.endTime to SortOrder.DESC).toList()
            }
    }

    val node by CheckedSchematicTable.nodeId.transform({ it?.let { EntityID(it, SchematicNodeTable) } }, { it?.value })
    val schemOwner by CheckedSchematicTable.nodeOwner.transform({ EntityID(it, SteamwarUserTable) }, { it.value })
    val nodeName by CheckedSchematicTable.nodeName
    val schemName get() = nodeName.value
    val validator by CheckedSchematicTable.validator.transform({ EntityID(it, SteamwarUserTable) }, { it.value })
    val startTimeId by CheckedSchematicTable.startTime
    val startTime get() = Timestamp.from(startTimeId.value)
    val endTime by CheckedSchematicTable.endTime.transform({ it.toInstant() }, { Timestamp.from(it) })
    val declineReason by CheckedSchematicTable.declineReason
    private var wasSeen by CheckedSchematicTable.seen
    var seen: Boolean
        get() = wasSeen
        set(value) = useDb { wasSeen = value }
    val nodeType by CheckedSchematicTable.nodeType
}