package com.xfestudio.xfeservermanager.infra.security;

import com.xfestudio.xfeservermanager.infra.persistence.PersistenceException;
import com.xfestudio.xfeservermanager.infra.persistence.SqliteDatabase;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.UUID;

public final class SqliteAuthRepository {
    private final SqliteDatabase database;

    public SqliteAuthRepository(SqliteDatabase database) {
        this.database = database;
    }

    public long countOwners() {
        try (var connection = database.openConnection();
                var statement = connection.prepareStatement(
                        "SELECT COUNT(*) FROM accounts WHERE role='owner' AND disabled=0");
                var result = statement.executeQuery()) {
            return result.next() ? result.getLong(1) : 0;
        } catch (SQLException exception) {
            throw new PersistenceException("cannot count owners", exception);
        }
    }

    public long countAccounts() {
        try (var connection = database.openConnection();
                var statement = connection.createStatement();
                var result = statement.executeQuery("SELECT COUNT(*) FROM accounts")) {
            return result.next() ? result.getLong(1) : 0;
        } catch (SQLException exception) {
            throw new PersistenceException("cannot count accounts", exception);
        }
    }

    public List<AccountRecord> listAccounts() {
        List<AccountRecord> accounts = new java.util.ArrayList<>();
        try (var connection = database.openConnection();
                var statement = connection.createStatement();
                var result = statement.executeQuery(
                        "SELECT * FROM accounts ORDER BY normalized_username, id")) {
            while (result.next()) {
                accounts.add(mapAccount(result));
            }
            return List.copyOf(accounts);
        } catch (SQLException exception) {
            throw new PersistenceException("cannot list accounts", exception);
        }
    }

    public void createAccount(AccountRecord account) {
        try (var connection = database.openConnection()) {
            insertAccount(connection, account);
        } catch (SQLException exception) {
            throw new PersistenceException("cannot create account", exception);
        }
    }

    /** Creates an account only if the authorizing account is still an enabled owner in this transaction. */
    public synchronized void createAccountAsOwner(UUID authorizingAccountId, AccountRecord account) {
        try (var connection = database.openConnection()) {
            connection.setAutoCommit(false);
            try {
                requireEnabledOwner(connection, authorizingAccountId);
                insertAccount(connection, account);
                connection.commit();
            } catch (RuntimeException | SQLException exception) {
                connection.rollback();
                throw exception;
            } finally {
                connection.setAutoCommit(true);
            }
        } catch (SQLException exception) {
            throw new PersistenceException("cannot create authorized account", exception);
        }
    }

    public Optional<AccountRecord> findByUsername(String username) {
        return findAccount("SELECT * FROM accounts WHERE normalized_username = ?", normalize(username));
    }

    public Optional<AccountRecord> findById(UUID id) {
        return findAccount("SELECT * FROM accounts WHERE id = ?", id.toString());
    }

    private Optional<AccountRecord> findAccount(String sql, String key) {
        try (var connection = database.openConnection(); var query = connection.prepareStatement(sql)) {
            query.setString(1, key);
            try (var result = query.executeQuery()) {
                return result.next() ? Optional.of(mapAccount(result)) : Optional.empty();
            }
        } catch (SQLException exception) {
            throw new PersistenceException("cannot read account", exception);
        }
    }

    public void recordLogin(UUID accountId, Instant when) {
        try (var connection = database.openConnection();
                var update = connection.prepareStatement(
                        "UPDATE accounts SET last_login_at=?, updated_at=? WHERE id=?")) {
            update.setLong(1, when.toEpochMilli());
            update.setLong(2, when.toEpochMilli());
            update.setString(3, accountId.toString());
            update.executeUpdate();
        } catch (SQLException exception) {
            throw new PersistenceException("cannot record login", exception);
        }
    }

    public void createSession(
            SessionRecord session, String remoteAddress, byte[] userAgentHash) {
        String sql = "INSERT INTO sessions(id, account_id, token_hash, csrf_hash, created_at, "
                + "last_seen_at, authenticated_at, totp_verified, expires_at, remote_address, "
                + "user_agent_hash) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try (var connection = database.openConnection(); var insert = connection.prepareStatement(sql)) {
            insert.setString(1, session.id().toString());
            insert.setString(2, session.accountId().toString());
            insert.setBytes(3, session.tokenHash());
            insert.setBytes(4, session.csrfHash());
            insert.setLong(5, session.createdAt().toEpochMilli());
            insert.setLong(6, session.lastSeenAt().toEpochMilli());
            insert.setLong(7, session.authenticatedAt().toEpochMilli());
            insert.setBoolean(8, session.totpVerified());
            insert.setLong(9, session.expiresAt().toEpochMilli());
            insert.setString(10, remoteAddress);
            insert.setBytes(11, userAgentHash);
            insert.executeUpdate();
        } catch (SQLException exception) {
            throw new PersistenceException("cannot create session", exception);
        }
    }

    public Optional<SessionRecord> findSessionByTokenHash(byte[] hash) {
        String sql = "SELECT * FROM sessions WHERE token_hash = ?";
        try (var connection = database.openConnection(); var query = connection.prepareStatement(sql)) {
            query.setBytes(1, hash);
            try (var result = query.executeQuery()) {
                return result.next() ? Optional.of(mapSession(result)) : Optional.empty();
            }
        } catch (SQLException exception) {
            throw new PersistenceException("cannot read session", exception);
        }
    }

    public List<StoredSessionSummary> listSessions(UUID accountId) {
        String sql = "SELECT id, created_at, last_seen_at, expires_at, remote_address "
                + "FROM sessions WHERE account_id=? AND revoked_at IS NULL "
                + "ORDER BY last_seen_at DESC, id";
        List<StoredSessionSummary> sessions = new java.util.ArrayList<>();
        try (var connection = database.openConnection(); var query = connection.prepareStatement(sql)) {
            query.setString(1, accountId.toString());
            try (var result = query.executeQuery()) {
                while (result.next()) {
                    sessions.add(new StoredSessionSummary(
                            UUID.fromString(result.getString("id")),
                            Instant.ofEpochMilli(result.getLong("created_at")),
                            Instant.ofEpochMilli(result.getLong("last_seen_at")),
                            Instant.ofEpochMilli(result.getLong("expires_at")),
                            result.getString("remote_address")));
                }
            }
            return List.copyOf(sessions);
        } catch (SQLException exception) {
            throw new PersistenceException("cannot list account sessions", exception);
        }
    }

    /** Revokes a session only when it belongs to the authenticated account. */
    public void revokeSession(UUID accountId, UUID sessionId, Instant when) {
        try (var connection = database.openConnection();
                var update = connection.prepareStatement(
                        "UPDATE sessions SET revoked_at=? WHERE id=? AND account_id=? "
                                + "AND revoked_at IS NULL")) {
            update.setLong(1, when.toEpochMilli());
            update.setString(2, sessionId.toString());
            update.setString(3, accountId.toString());
            update.executeUpdate();
        } catch (SQLException exception) {
            throw new PersistenceException("cannot revoke account session", exception);
        }
    }

    public void touchSession(UUID sessionId, Instant when) {
        try (var connection = database.openConnection();
                var update = connection.prepareStatement(
                        "UPDATE sessions SET last_seen_at=? WHERE id=? AND revoked_at IS NULL")) {
            update.setLong(1, when.toEpochMilli());
            update.setString(2, sessionId.toString());
            update.executeUpdate();
        } catch (SQLException exception) {
            throw new PersistenceException("cannot update session", exception);
        }
    }

    public void markReauthenticated(UUID sessionId, Instant when) {
        try (var connection = database.openConnection();
                var update = connection.prepareStatement(
                        "UPDATE sessions SET authenticated_at=?, last_seen_at=? WHERE id=? AND revoked_at IS NULL")) {
            update.setLong(1, when.toEpochMilli());
            update.setLong(2, when.toEpochMilli());
            update.setString(3, sessionId.toString());
            update.executeUpdate();
        } catch (SQLException exception) {
            throw new PersistenceException("cannot update session authentication", exception);
        }
    }

    public void revokeSession(UUID sessionId, Instant when) {
        try (var connection = database.openConnection();
                var update = connection.prepareStatement(
                        "UPDATE sessions SET revoked_at=? WHERE id=? AND revoked_at IS NULL")) {
            update.setLong(1, when.toEpochMilli());
            update.setString(2, sessionId.toString());
            update.executeUpdate();
        } catch (SQLException exception) {
            throw new PersistenceException("cannot revoke session", exception);
        }
    }

    public void revokeAccountSessions(UUID accountId, Instant when) {
        try (var connection = database.openConnection();
                var update = connection.prepareStatement(
                        "UPDATE sessions SET revoked_at=? WHERE account_id=? AND revoked_at IS NULL")) {
            update.setLong(1, when.toEpochMilli());
            update.setString(2, accountId.toString());
            update.executeUpdate();
        } catch (SQLException exception) {
            throw new PersistenceException("cannot revoke account sessions", exception);
        }
    }

    public void revokeOtherSessions(UUID accountId, UUID retainedSessionId, Instant when) {
        try (var connection = database.openConnection();
                var update = connection.prepareStatement(
                        "UPDATE sessions SET revoked_at=? WHERE account_id=? AND id<>? AND revoked_at IS NULL")) {
            update.setLong(1, when.toEpochMilli());
            update.setString(2, accountId.toString());
            update.setString(3, retainedSessionId.toString());
            update.executeUpdate();
        } catch (SQLException exception) {
            throw new PersistenceException("cannot revoke other account sessions", exception);
        }
    }

    public void purgeExpiredSessions(Instant now) {
        try (var connection = database.openConnection();
                var delete = connection.prepareStatement(
                        "DELETE FROM sessions WHERE expires_at < ? OR revoked_at IS NOT NULL")) {
            delete.setLong(1, now.toEpochMilli());
            delete.executeUpdate();
        } catch (SQLException exception) {
            throw new PersistenceException("cannot purge sessions", exception);
        }
    }

    /** Bounds active session growth for an account and removes its revoked/expired rows. */
    public void pruneAccountSessions(
            UUID accountId, int maximumActive, Instant now, Instant idleCutoff) {
        if (maximumActive < 1) {
            throw new IllegalArgumentException("maximumActive must be positive");
        }
        try (var connection = database.openConnection()) {
            connection.setAutoCommit(false);
            try (var revoke = connection.prepareStatement(
                            "UPDATE sessions SET revoked_at=? WHERE account_id=? "
                                    + "AND revoked_at IS NULL AND id NOT IN ("
                                    + "SELECT id FROM sessions WHERE account_id=? "
                                    + "AND revoked_at IS NULL AND expires_at>? AND last_seen_at>? "
                                    + "ORDER BY created_at DESC, id DESC LIMIT ?)");
                    var delete = connection.prepareStatement(
                            "DELETE FROM sessions WHERE account_id=? "
                                    + "AND (revoked_at IS NOT NULL OR expires_at<=? OR last_seen_at<=?)")) {
                revoke.setLong(1, now.toEpochMilli());
                revoke.setString(2, accountId.toString());
                revoke.setString(3, accountId.toString());
                revoke.setLong(4, now.toEpochMilli());
                revoke.setLong(5, idleCutoff.toEpochMilli());
                revoke.setInt(6, maximumActive);
                revoke.executeUpdate();
                delete.setString(1, accountId.toString());
                delete.setLong(2, now.toEpochMilli());
                delete.setLong(3, idleCutoff.toEpochMilli());
                delete.executeUpdate();
                connection.commit();
            } catch (RuntimeException | SQLException exception) {
                connection.rollback();
                throw exception;
            } finally {
                connection.setAutoCommit(true);
            }
        } catch (SQLException exception) {
            throw new PersistenceException("cannot prune account sessions", exception);
        }
    }

    public void enableTotpWithRecoveryCodes(
            UUID accountId,
            byte[] encryptedSecret,
            long acceptedCounter,
            List<byte[]> codeHashes,
            UUID retainedSessionId,
            Instant when) {
        String insertSql = "INSERT INTO recovery_codes(account_id, code_hash, created_at) VALUES(?, ?, ?)";
        try (var connection = database.openConnection()) {
            connection.setAutoCommit(false);
            try (var update = connection.prepareStatement(
                            "UPDATE accounts SET totp_secret=?, totp_enabled=1, "
                                    + "totp_last_counter=?, updated_at=? WHERE id=?");
                    var delete = connection.prepareStatement(
                            "DELETE FROM recovery_codes WHERE account_id=?");
                    var insert = connection.prepareStatement(insertSql);
                    var revoke = connection.prepareStatement(
                            "UPDATE sessions SET revoked_at=? WHERE account_id=? AND id<>? "
                                    + "AND revoked_at IS NULL");
                    var assure = connection.prepareStatement(
                            "UPDATE sessions SET totp_verified=1, last_seen_at=? "
                                    + "WHERE id=? AND account_id=? AND revoked_at IS NULL")) {
                update.setBytes(1, encryptedSecret);
                update.setLong(2, acceptedCounter);
                update.setLong(3, when.toEpochMilli());
                update.setString(4, accountId.toString());
                if (update.executeUpdate() != 1) {
                    throw new PersistenceException("account does not exist");
                }
                delete.setString(1, accountId.toString());
                delete.executeUpdate();
                for (byte[] codeHash : codeHashes) {
                    insert.setString(1, accountId.toString());
                    insert.setBytes(2, codeHash);
                    insert.setLong(3, when.toEpochMilli());
                    insert.addBatch();
                }
                insert.executeBatch();
                revoke.setLong(1, when.toEpochMilli());
                revoke.setString(2, accountId.toString());
                revoke.setString(3, retainedSessionId.toString());
                revoke.executeUpdate();
                assure.setLong(1, when.toEpochMilli());
                assure.setString(2, retainedSessionId.toString());
                assure.setString(3, accountId.toString());
                if (assure.executeUpdate() != 1) {
                    throw new PersistenceException("retained session is unavailable");
                }
                connection.commit();
            } catch (RuntimeException | SQLException exception) {
                connection.rollback();
                throw exception;
            } finally {
                connection.setAutoCommit(true);
            }
        } catch (SQLException exception) {
            throw new PersistenceException("cannot enable TOTP", exception);
        }
    }

    public void replaceRecoveryCodes(UUID accountId, List<byte[]> codeHashes, Instant when) {
        String insertSql = "INSERT INTO recovery_codes(account_id, code_hash, created_at) VALUES(?, ?, ?)";
        try (var connection = database.openConnection()) {
            connection.setAutoCommit(false);
            try (var delete = connection.prepareStatement(
                            "DELETE FROM recovery_codes WHERE account_id=?");
                    var insert = connection.prepareStatement(insertSql)) {
                delete.setString(1, accountId.toString());
                delete.executeUpdate();
                for (byte[] codeHash : codeHashes) {
                    insert.setString(1, accountId.toString());
                    insert.setBytes(2, codeHash);
                    insert.setLong(3, when.toEpochMilli());
                    insert.addBatch();
                }
                insert.executeBatch();
                connection.commit();
            } catch (SQLException exception) {
                connection.rollback();
                throw exception;
            } finally {
                connection.setAutoCommit(true);
            }
        } catch (SQLException exception) {
            throw new PersistenceException("cannot replace recovery codes", exception);
        }
    }

    public boolean consumeRecoveryCode(UUID accountId, byte[] codeHash, Instant when) {
        String sql = "UPDATE recovery_codes SET used_at=? "
                + "WHERE account_id=? AND code_hash=? AND used_at IS NULL";
        try (var connection = database.openConnection(); var update = connection.prepareStatement(sql)) {
            update.setLong(1, when.toEpochMilli());
            update.setString(2, accountId.toString());
            update.setBytes(3, codeHash);
            return update.executeUpdate() == 1;
        } catch (SQLException exception) {
            throw new PersistenceException("cannot consume recovery code", exception);
        }
    }

    /** Atomically accepts each TOTP time-step at most once, including across restarts. */
    public boolean consumeTotpCounter(UUID accountId, long counter, Instant when) {
        String sql = "UPDATE accounts SET totp_last_counter=?, updated_at=? WHERE id=? "
                + "AND totp_enabled=1 AND (totp_last_counter IS NULL OR totp_last_counter < ?)";
        try (var connection = database.openConnection(); var update = connection.prepareStatement(sql)) {
            update.setLong(1, counter);
            update.setLong(2, when.toEpochMilli());
            update.setString(3, accountId.toString());
            update.setLong(4, counter);
            return update.executeUpdate() == 1;
        } catch (SQLException exception) {
            throw new PersistenceException("cannot consume TOTP counter", exception);
        }
    }

    public boolean consumeTotpCounterAndMarkSession(
            UUID accountId, UUID sessionId, long counter, Instant when) {
        try (var connection = database.openConnection()) {
            connection.setAutoCommit(false);
            try (var consume = connection.prepareStatement(
                            "UPDATE accounts SET totp_last_counter=?, updated_at=? WHERE id=? "
                                    + "AND totp_enabled=1 "
                                    + "AND (totp_last_counter IS NULL OR totp_last_counter < ?)");
                    var assure = connection.prepareStatement(
                            "UPDATE sessions SET totp_verified=1, authenticated_at=?, last_seen_at=? "
                                    + "WHERE id=? AND account_id=? AND revoked_at IS NULL")) {
                consume.setLong(1, counter);
                consume.setLong(2, when.toEpochMilli());
                consume.setString(3, accountId.toString());
                consume.setLong(4, counter);
                if (consume.executeUpdate() != 1) {
                    connection.rollback();
                    return false;
                }
                assure.setLong(1, when.toEpochMilli());
                assure.setLong(2, when.toEpochMilli());
                assure.setString(3, sessionId.toString());
                assure.setString(4, accountId.toString());
                if (assure.executeUpdate() != 1) {
                    throw new PersistenceException("session is unavailable");
                }
                connection.commit();
                return true;
            } catch (RuntimeException | SQLException exception) {
                connection.rollback();
                throw exception;
            } finally {
                connection.setAutoCommit(true);
            }
        } catch (SQLException exception) {
            throw new PersistenceException("cannot consume TOTP and reauthenticate session", exception);
        }
    }

    public boolean consumeRecoveryCodeAndMarkSession(
            UUID accountId, UUID sessionId, byte[] codeHash, Instant when) {
        try (var connection = database.openConnection()) {
            connection.setAutoCommit(false);
            try (var consume = connection.prepareStatement(
                            "UPDATE recovery_codes SET used_at=? WHERE account_id=? AND code_hash=? "
                                    + "AND used_at IS NULL");
                    var reauthenticate = connection.prepareStatement(
                            "UPDATE sessions SET authenticated_at=?, last_seen_at=? "
                                    + "WHERE id=? AND account_id=? AND revoked_at IS NULL")) {
                consume.setLong(1, when.toEpochMilli());
                consume.setString(2, accountId.toString());
                consume.setBytes(3, codeHash);
                if (consume.executeUpdate() != 1) {
                    connection.rollback();
                    return false;
                }
                reauthenticate.setLong(1, when.toEpochMilli());
                reauthenticate.setLong(2, when.toEpochMilli());
                reauthenticate.setString(3, sessionId.toString());
                reauthenticate.setString(4, accountId.toString());
                if (reauthenticate.executeUpdate() != 1) {
                    throw new PersistenceException("session is unavailable");
                }
                connection.commit();
                return true;
            } catch (RuntimeException | SQLException exception) {
                connection.rollback();
                throw exception;
            } finally {
                connection.setAutoCommit(true);
            }
        } catch (SQLException exception) {
            throw new PersistenceException("cannot consume recovery code and reauthenticate session", exception);
        }
    }

    /** Changes an account role while transactionally protecting the final enabled owner. */
    public synchronized void changeRole(UUID accountId, Role role, Instant when) {
        try (var connection = database.openConnection()) {
            connection.setAutoCommit(false);
            try {
                Role previous;
                boolean disabled;
                try (var select = connection.prepareStatement(
                        "SELECT role, disabled FROM accounts WHERE id=?")) {
                    select.setString(1, accountId.toString());
                    try (var result = select.executeQuery()) {
                        if (!result.next()) {
                            throw new PersistenceException("account does not exist");
                        }
                        previous = Role.fromWireName(result.getString(1));
                        disabled = result.getBoolean(2);
                    }
                }
                if (previous == Role.OWNER && role != Role.OWNER && !disabled
                        && enabledOwnerCount(connection) <= 1) {
                    throw new AccountConflictException("cannot demote the final owner");
                }
                try (var update = connection.prepareStatement(
                        "UPDATE accounts SET role=?, updated_at=? WHERE id=?")) {
                    update.setString(1, role.wireName());
                    update.setLong(2, when.toEpochMilli());
                    update.setString(3, accountId.toString());
                    update.executeUpdate();
                }
                connection.commit();
            } catch (RuntimeException | SQLException exception) {
                connection.rollback();
                throw exception;
            } finally {
                connection.setAutoCommit(true);
            }
        } catch (SQLException exception) {
            throw new PersistenceException("cannot change account role", exception);
        }
    }

    /** Enables/disables an account while transactionally protecting the final enabled owner. */
    public synchronized void setDisabled(UUID accountId, boolean disabled, Instant when) {
        try (var connection = database.openConnection()) {
            connection.setAutoCommit(false);
            try {
                Role role;
                boolean wasDisabled;
                try (var select = connection.prepareStatement(
                        "SELECT role, disabled FROM accounts WHERE id=?")) {
                    select.setString(1, accountId.toString());
                    try (var result = select.executeQuery()) {
                        if (!result.next()) {
                            throw new PersistenceException("account does not exist");
                        }
                        role = Role.fromWireName(result.getString(1));
                        wasDisabled = result.getBoolean(2);
                    }
                }
                if (disabled && !wasDisabled && role == Role.OWNER && enabledOwnerCount(connection) <= 1) {
                    throw new AccountConflictException("cannot disable the final owner");
                }
                try (var update = connection.prepareStatement(
                        "UPDATE accounts SET disabled=?, updated_at=? WHERE id=?")) {
                    update.setBoolean(1, disabled);
                    update.setLong(2, when.toEpochMilli());
                    update.setString(3, accountId.toString());
                    update.executeUpdate();
                }
                connection.commit();
            } catch (RuntimeException | SQLException exception) {
                connection.rollback();
                throw exception;
            } finally {
                connection.setAutoCommit(true);
            }
        } catch (SQLException exception) {
            throw new PersistenceException("cannot update account", exception);
        }
    }

    /** Deletes an account while transactionally protecting the final enabled owner. */
    public synchronized void deleteAccount(UUID accountId) {
        deleteAccount(null, accountId);
    }

    /** Deletes an account after rechecking the owner's authority in the same transaction. */
    public synchronized void deleteAccountAsOwner(UUID authorizingAccountId, UUID accountId) {
        deleteAccount(java.util.Objects.requireNonNull(authorizingAccountId, "authorizingAccountId"), accountId);
    }

    private void deleteAccount(UUID authorizingAccountId, UUID accountId) {
        try (var connection = database.openConnection()) {
            connection.setAutoCommit(false);
            try {
                if (authorizingAccountId != null) {
                    requireEnabledOwner(connection, authorizingAccountId);
                }
                Role role;
                boolean disabled;
                try (var select = connection.prepareStatement(
                        "SELECT role, disabled FROM accounts WHERE id=?")) {
                    select.setString(1, accountId.toString());
                    try (var result = select.executeQuery()) {
                        if (!result.next()) {
                            return;
                        }
                        role = Role.fromWireName(result.getString(1));
                        disabled = result.getBoolean(2);
                    }
                }
                if (role == Role.OWNER && !disabled && enabledOwnerCount(connection) <= 1) {
                    throw new AccountConflictException("cannot delete the final owner");
                }
                try (var delete = connection.prepareStatement("DELETE FROM accounts WHERE id=?")) {
                    delete.setString(1, accountId.toString());
                    delete.executeUpdate();
                }
                connection.commit();
            } catch (RuntimeException | SQLException exception) {
                connection.rollback();
                throw exception;
            } finally {
                connection.setAutoCommit(true);
            }
        } catch (SQLException exception) {
            throw new PersistenceException("cannot delete account", exception);
        }
    }

    /** Atomically updates role/disabled state and revokes affected sessions. */
    public synchronized AccountRecord updateAccount(
            UUID accountId, Role requestedRole, Boolean requestedDisabled, Instant when) {
        return updateAccount(null, accountId, requestedRole, requestedDisabled, when);
    }

    /** Updates an account after rechecking the owner's authority in the same transaction. */
    public synchronized AccountRecord updateAccountAsOwner(
            UUID authorizingAccountId,
            UUID accountId,
            Role requestedRole,
            Boolean requestedDisabled,
            Instant when) {
        return updateAccount(java.util.Objects.requireNonNull(authorizingAccountId, "authorizingAccountId"),
                accountId, requestedRole, requestedDisabled, when);
    }

    private AccountRecord updateAccount(
            UUID authorizingAccountId,
            UUID accountId,
            Role requestedRole,
            Boolean requestedDisabled,
            Instant when) {
        try (var connection = database.openConnection()) {
            connection.setAutoCommit(false);
            try {
                if (authorizingAccountId != null) {
                    requireEnabledOwner(connection, authorizingAccountId);
                }
                AccountRecord current;
                try (var select = connection.prepareStatement("SELECT * FROM accounts WHERE id=?")) {
                    select.setString(1, accountId.toString());
                    try (var result = select.executeQuery()) {
                        if (!result.next()) {
                            throw new java.util.NoSuchElementException("account does not exist");
                        }
                        current = mapAccount(result);
                    }
                }
                Role nextRole = requestedRole == null ? current.role() : requestedRole;
                boolean nextDisabled = requestedDisabled == null
                        ? current.disabled()
                        : requestedDisabled;
                boolean removesEnabledOwner = current.role() == Role.OWNER
                        && !current.disabled()
                        && (nextRole != Role.OWNER || nextDisabled);
                if (removesEnabledOwner && enabledOwnerCount(connection) <= 1) {
                    throw new AccountConflictException("cannot modify the final owner");
                }
                try (var update = connection.prepareStatement(
                        "UPDATE accounts SET role=?, disabled=?, updated_at=? WHERE id=?")) {
                    update.setString(1, nextRole.wireName());
                    update.setBoolean(2, nextDisabled);
                    update.setLong(3, when.toEpochMilli());
                    update.setString(4, accountId.toString());
                    if (update.executeUpdate() != 1) {
                        throw new java.util.NoSuchElementException("account does not exist");
                    }
                }
                if (nextDisabled || nextRole != current.role()) {
                    try (var revoke = connection.prepareStatement(
                            "UPDATE sessions SET revoked_at=? WHERE account_id=? "
                                    + "AND revoked_at IS NULL")) {
                        revoke.setLong(1, when.toEpochMilli());
                        revoke.setString(2, accountId.toString());
                        revoke.executeUpdate();
                    }
                }
                connection.commit();
                return new AccountRecord(
                        current.id(),
                        current.username(),
                        current.normalizedUsername(),
                        current.passwordHash(),
                        nextRole,
                        current.encryptedTotpSecret(),
                        current.totpEnabled(),
                        nextDisabled,
                        current.createdAt(),
                        when,
                        current.lastLoginAt());
            } catch (RuntimeException | SQLException exception) {
                connection.rollback();
                throw exception;
            } finally {
                connection.setAutoCommit(true);
            }
        } catch (SQLException exception) {
            throw new PersistenceException("cannot update account", exception);
        }
    }

    private static long enabledOwnerCount(java.sql.Connection connection) throws SQLException {
        try (var query = connection.prepareStatement(
                        "SELECT COUNT(*) FROM accounts WHERE role='owner' AND disabled=0");
                var result = query.executeQuery()) {
            return result.next() ? result.getLong(1) : 0;
        }
    }

    public static String normalize(String username) {
        if (username == null) {
            return "";
        }
        return username.strip().toLowerCase(Locale.ROOT);
    }

    private static AccountRecord mapAccount(ResultSet result) throws SQLException {
        Long lastLogin = nullableLong(result, "last_login_at");
        return new AccountRecord(
                UUID.fromString(result.getString("id")),
                result.getString("username"),
                result.getString("normalized_username"),
                result.getString("password_hash"),
                Role.fromWireName(result.getString("role")),
                result.getBytes("totp_secret"),
                result.getBoolean("totp_enabled"),
                result.getBoolean("disabled"),
                Instant.ofEpochMilli(result.getLong("created_at")),
                Instant.ofEpochMilli(result.getLong("updated_at")),
                lastLogin == null ? null : Instant.ofEpochMilli(lastLogin));
    }

    private static void requireEnabledOwner(Connection connection, UUID accountId) throws SQLException {
        try (var select = connection.prepareStatement(
                "SELECT 1 FROM accounts WHERE id=? AND role='owner' AND disabled=0")) {
            select.setString(1, accountId.toString());
            try (var result = select.executeQuery()) {
                if (!result.next()) {
                    throw new SecurityException("the authorizing account is no longer an enabled owner");
                }
            }
        }
    }

    private static void insertAccount(Connection connection, AccountRecord account) throws SQLException {
        String sql = "INSERT INTO accounts(id, username, normalized_username, password_hash, role, "
                + "totp_secret, totp_enabled, disabled, created_at, updated_at, last_login_at) "
                + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try (var insert = connection.prepareStatement(sql)) {
            insert.setString(1, account.id().toString());
            insert.setString(2, account.username());
            insert.setString(3, account.normalizedUsername());
            insert.setString(4, account.passwordHash());
            insert.setString(5, account.role().wireName());
            insert.setBytes(6, account.encryptedTotpSecret());
            insert.setBoolean(7, account.totpEnabled());
            insert.setBoolean(8, account.disabled());
            insert.setLong(9, account.createdAt().toEpochMilli());
            insert.setLong(10, account.updatedAt().toEpochMilli());
            if (account.lastLoginAt() == null) {
                insert.setNull(11, java.sql.Types.BIGINT);
            } else {
                insert.setLong(11, account.lastLoginAt().toEpochMilli());
            }
            insert.executeUpdate();
        }
    }

    private static SessionRecord mapSession(ResultSet result) throws SQLException {
        Long revoked = nullableLong(result, "revoked_at");
        return new SessionRecord(
                UUID.fromString(result.getString("id")),
                UUID.fromString(result.getString("account_id")),
                result.getBytes("token_hash"),
                result.getBytes("csrf_hash"),
                Instant.ofEpochMilli(result.getLong("created_at")),
                Instant.ofEpochMilli(result.getLong("last_seen_at")),
                Instant.ofEpochMilli(result.getLong("authenticated_at")),
                result.getBoolean("totp_verified"),
                Instant.ofEpochMilli(result.getLong("expires_at")),
                revoked == null ? null : Instant.ofEpochMilli(revoked));
    }

    private static Long nullableLong(ResultSet result, String name) throws SQLException {
        long value = result.getLong(name);
        return result.wasNull() ? null : value;
    }

    public record StoredSessionSummary(
            UUID id,
            Instant createdAt,
            Instant lastSeenAt,
            Instant expiresAt,
            String remoteAddress) { }
}
