/* © SRSoftware 2025 */
package de.srsoftware.umbrella.journal;

import static de.srsoftware.tools.jdbc.Query.insertInto;
import static de.srsoftware.umbrella.core.constants.Field.*;
import static de.srsoftware.umbrella.core.exceptions.UmbrellaException.databaseException;
import static de.srsoftware.umbrella.core.exceptions.UmbrellaException.failedToCreateTable;
import static de.srsoftware.umbrella.journal.Constants.ERROR_WRITE_EVENT;
import static de.srsoftware.umbrella.journal.Constants.TABLE_JOURNAL;
import static java.text.MessageFormat.format;

import de.srsoftware.umbrella.core.BaseDb;
import de.srsoftware.umbrella.messagebus.events.Event;
import java.sql.Connection;
import java.sql.SQLException;

public class SqliteDb extends BaseDb implements JournalDb{
	public SqliteDb(Connection connection) {
		super(connection);
	}

	protected int createTables() {
		int currentVersion = createSettingsTable();
		switch (currentVersion){
			case 0:
				createJournalTable();
		}

		return setCurrentVersion(1);
	}

	private void createJournalTable() {
		var sql = """
				CREATE TABLE IF NOT EXISTS {0} (
					{1} INTEGER PRIMARY KEY,
					{2} INTEGER,
					{3} VARCHAR(255) NOT NULL,
					{4} VARCHAR(16) NOT NULL,
					{5} TEXT
				);
				""";
		sql = format(sql,TABLE_JOURNAL,ID,USER_ID,MODULE,ACTION,DESCRIPTION);
		try {
			db.prepareStatement(sql).execute();
		} catch (SQLException e) {
			throw failedToCreateTable(TABLE_JOURNAL);
		}
	}

	@Override
	public void logEvent(Event<?> event) {
		try {
			insertInto(TABLE_JOURNAL,USER_ID,MODULE,ACTION,DESCRIPTION)
					.values(event.initiator().id(), event.module(), event.eventType(), event.describe())
					.execute(db).close();
		} catch (SQLException e) {
			throw databaseException(ERROR_WRITE_EVENT,event.eventType(),event.initiator().name());
		}
	}
}
