/*
 *   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.CompositeID
import org.jetbrains.exposed.v1.core.dao.id.CompositeIdTable
import org.jetbrains.exposed.v1.core.dao.id.EntityID
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.dao.CompositeEntity
import org.jetbrains.exposed.v1.dao.CompositeEntityClass

object RefereeTable : CompositeIdTable("Referee") {
    val eventId = reference("EventId", EventTable)
    val userId = reference("UserId", SteamwarUserTable).index()

    override val primaryKey = PrimaryKey(eventId, userId)

    init {
        addIdColumn(eventId)
        addIdColumn(userId)
    }
}

class Referee(id: EntityID<CompositeID>) : CompositeEntity(id) {
    companion object : CompositeEntityClass<Referee>(RefereeTable) {
        @JvmStatic
        fun add(eventId: Int, userId: Int) =
            useDb {
                new {
                    this.eventID = eventId
                    this.userID = userId
                }
            }

        @JvmStatic
        fun remove(eventId: Int, userId: Int) =
            useDb {
                find { (RefereeTable.eventId eq eventId) and (RefereeTable.userId eq userId) }.firstOrNull()?.delete()
            }

        @JvmStatic
        fun get(event: Int) =
            useDb {
                find { RefereeTable.eventId eq event }.map { it.userID }.toSet()
            }
    }

    var eventID by RefereeTable.eventId.transform({ EntityID(it, EventTable) }, { it.value })
    var userID by RefereeTable.userId.transform({ EntityID(it, SteamwarUserTable) }, { it.value })
}