/*
 *   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.Statement;
import de.steamwar.sql.internal.Table;
import lombok.AllArgsConstructor;

import java.io.File;
import java.sql.Timestamp;

@AllArgsConstructor
public class SWException {

    public static void init() {
        // force class initialialisation
    }

    private static final String CWD = System.getProperty("user.dir");
    private static final String SERVER_NAME = new File(CWD).getName();

    private static final Table<SWException> table = new Table<>(SWException.class, "Exception");
    private static final Statement insert = table.insertFields(true, "server", "message", "stacktrace");

    @Field(keys = {Table.PRIMARY}, autoincrement = true)
    private final int id;
    @Field(def = "CURRENT_TIMESTAMP")
    private final Timestamp time;
    @Field
    private final String server;
    @Field
    private final String message;
    @Field
    private final String stacktrace;

    public static void log(String message, String stacktrace){
        insert.update(SERVER_NAME, generateMessage(message), stacktrace);
    }

    public static int logGetId(String message, String stacktrace) {
        return insert.insertGetKey(SERVER_NAME, generateMessage(message), stacktrace);
    }

    private static String generateMessage(String message) {
        StringBuilder msgBuilder = new StringBuilder(message);
        SQLWrapper.impl.additionalExceptionMetadata(msgBuilder);
        msgBuilder.append("\nCWD: ").append(CWD);
        return msgBuilder.toString();
    }
}
