package com.alttd.altitudeweb.setup;

import com.alttd.altitudeweb.database.Databases;
import com.alttd.altitudeweb.database.web_db.SettingsMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

import java.sql.SQLException;
import java.sql.Statement;

@Slf4j
public class InitializeWebDb {

    protected static void init() {
        log.info("Initializing LiteBans");
        Connection.getConnection(Databases.DEFAULT, (configuration) -> {
                    configuration.addMapper(SettingsMapper.class);
                }).join()
                .runQuery(InitializeWebDb::createSettingsTable);
        log.debug("Initialized LuckPerms");
    }

    private static void createSettingsTable(SqlSession sqlSession) {
        String query = """
                CREATE TABLE IF NOT EXISTS db_connection_settings
                (
                    internal_name     VARCHAR(255) NOT NULL,
                    name              VARCHAR(255) NOT NULL,
                    username          VARCHAR(255) NOT NULL,
                    password          VARCHAR(255) NOT NULL,
                    host              VARCHAR(255) NOT NULL,
                    port              INT NOT NULL,
                    CONSTRAINT pk_internal_name PRIMARY KEY (internal_name)
                );
                """;
        try (Statement statement = sqlSession.getConnection().createStatement()) {
            statement.execute(query);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
