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

import static de.srsoftware.tools.jdbc.Condition.equal;
import static de.srsoftware.tools.jdbc.Query.SelectQuery.ALL;
import static de.srsoftware.tools.jdbc.Query.select;
import static de.srsoftware.umbrella.core.Errors.FAILED_TO_CHECK_FILE_PERMISSIONS;
import static de.srsoftware.umbrella.core.constants.Field.USER_ID;
import static de.srsoftware.umbrella.core.exceptions.UmbrellaException.databaseException;
import static de.srsoftware.umbrella.core.exceptions.UmbrellaException.failedToCreateTable;
import static de.srsoftware.umbrella.files.Constants.FILE;
import static de.srsoftware.umbrella.files.Constants.TABLE_FILE_SHARES;
import static java.text.MessageFormat.format;

import de.srsoftware.umbrella.core.BaseDb;
import de.srsoftware.umbrella.core.model.UmbrellaUser;
import java.sql.Connection;
import java.sql.SQLException;

public class SqliteDb extends BaseDb implements FileDb {

	public SqliteDb(Connection conn) {
		super(conn);
	}

	@Override
	protected int createTables() {
		int currentVersion = createSettingsTable();
		switch (currentVersion){
			case 0:
				createShareTable();
		}

		return setCurrentVersion(1);
	}

	private void createShareTable() {
		var sql = "CREATE TABLE IF NOT EXISTS {0} ({1} VARCHAR(2048) NOT NULL, {2} INT NOT NULL, PRIMARY KEY({1}, {2}))";
		try {
			db.prepareStatement(format(sql, TABLE_FILE_SHARES,FILE, USER_ID)).execute();
		} catch (SQLException e){
			throw failedToCreateTable(TABLE_FILE_SHARES).causedBy(e);
		}
	}

	@Override
	public boolean isPermitted(UmbrellaUser user, String fileName) {
		try {
			var rs = select(ALL).from(TABLE_FILE_SHARES).where(USER_ID, equal(user.id())).where(FILE, equal(fileName)).exec(db);
			var result = rs.next();
			rs.close();
			return result;
		} catch (SQLException e) {
			throw databaseException(FAILED_TO_CHECK_FILE_PERMISSIONS);
		}
	}
}
