/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 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.Field;
import de.steamwar.sql.internal.SelectStatement;
import de.steamwar.sql.internal.Statement;
import de.steamwar.sql.internal.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.sql.Timestamp;
import java.time.Instant;
import java.util.List;

@AllArgsConstructor
public class BannedUserIPs {

    private static final Table<BannedUserIPs> table = new Table<>(BannedUserIPs.class);

    private static final SelectStatement<BannedUserIPs> getByID = table.selectFields("UserID");
    private static final SelectStatement<BannedUserIPs> getByIP = new SelectStatement<>(table, "SELECT * FROM BannedUserIPs WHERE IP = ? ORDER BY Timestamp DESC");
    private static final Statement banIP = table.insertAll();
    private static final Statement unbanIPs = table.deleteFields("UserID");

    @Getter
    @Field(keys = {Table.PRIMARY})
    private final int userID;
    @Getter
    @Field(def = "CURRENT_TIMESTAMP")
    private final Timestamp timestamp;
    @Field(keys = {Table.PRIMARY})
    private final String ip;

    public static List<BannedUserIPs> get(int userID) {
        return getByID.listSelect(userID);
    }

    public static List<BannedUserIPs> get(String ip) {
        return getByIP.listSelect(ip);
    }

    public static void banIP(int userID, String ip){
        banIP.update(userID, Timestamp.from(Instant.now()), ip);
    }

    public static void unbanIPs(int userID) {
        unbanIPs.update(userID);
    }
}
