package com.xfestudio.xfeservermanager.infra.security;

import com.xfestudio.xfeservermanager.infra.config.ServerConfiguration;
import java.nio.charset.StandardCharsets;
import java.net.URLEncoder;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;

public final class AuthenticationService {
    private static final Duration SESSION_TOUCH_INTERVAL = Duration.ofMinutes(1);
    private static final Duration TOTP_ENROLLMENT_LIFETIME = Duration.ofMinutes(10);
    private static final String DUMMY_PASSWORD = "not-a-real-password-credential";
    private static final int RECOVERY_CODE_COUNT = 10;
    private static final int MAXIMUM_ACTIVE_SESSIONS_PER_ACCOUNT = 20;
    private static final int MAXIMUM_MANAGEMENT_ACCOUNTS = 100;
    private static final int MAXIMUM_SECOND_FACTOR_ATTEMPTS = 3;
    private static final Duration SECOND_FACTOR_ATTEMPT_WINDOW = Duration.ofMinutes(10);

    private final SqliteAuthRepository repository;
    private final PasswordHasher passwordHasher;
    private final TotpService totpService;
    private final AesGcmSecretBox secretBox;
    private final BootstrapTokenService bootstrapTokens;
    private final SlidingWindowRateLimiter rateLimiter;
    private final SlidingWindowRateLimiter secondFactorRateLimiter;
    private final ServerConfiguration configuration;
    private final Clock clock;
    private final String dummyPasswordHash;
    private final Semaphore passwordSlots = new Semaphore(4, true);
    private final ConcurrentHashMap<UUID, PendingTotpEnrollment> pendingTotp =
            new ConcurrentHashMap<>();

    public AuthenticationService(
            SqliteAuthRepository repository,
            PasswordHasher passwordHasher,
            TotpService totpService,
            AesGcmSecretBox secretBox,
            BootstrapTokenService bootstrapTokens,
            SlidingWindowRateLimiter rateLimiter,
            ServerConfiguration configuration,
            Clock clock) {
        this.repository = repository;
        this.passwordHasher = passwordHasher;
        this.totpService = totpService;
        this.secretBox = secretBox;
        this.bootstrapTokens = bootstrapTokens;
        this.rateLimiter = rateLimiter;
        this.configuration = configuration;
        this.clock = clock;
        this.secondFactorRateLimiter = new SlidingWindowRateLimiter(
                MAXIMUM_SECOND_FACTOR_ATTEMPTS, SECOND_FACTOR_ATTEMPT_WINDOW, clock);
        char[] dummy = DUMMY_PASSWORD.toCharArray();
        try {
            this.dummyPasswordHash = passwordHasher.hash(dummy);
        } finally {
            Arrays.fill(dummy, '\0');
        }
    }

    public synchronized IssuedSession createInitialOwner(
            String bootstrapToken,
            String username,
            char[] password,
            String remoteAddress,
            String userAgent) {
        char[] suppliedPassword = password == null ? new char[0] : password;
        try {
            if (repository.countOwners() != 0) {
                throw new AuthenticationException("setup_complete", "an owner already exists");
            }
            validateUsername(username);
            if (suppliedPassword.length < 12 || suppliedPassword.length > 1_024) {
                throw new AuthenticationException(
                        "invalid_password", "password must contain 12 to 1024 characters");
            }
            String passwordHash;
            acquirePasswordSlot();
            try {
                if (!bootstrapTokens.consume(bootstrapToken)) {
                    throw new AuthenticationException(
                            "invalid_bootstrap_token", "setup token is invalid or expired");
                }
                passwordHash = passwordHasher.hash(suppliedPassword);
            } finally {
                passwordSlots.release();
            }
            Instant now = clock.instant();
            UUID accountId = UUID.randomUUID();
            String normalized = SqliteAuthRepository.normalize(username);
            repository.createAccount(new AccountRecord(
                    accountId,
                    username.strip(),
                    normalized,
                    passwordHash,
                    Role.OWNER,
                    null,
                    false,
                    false,
                    now,
                    now,
                    null));
            return issueSession(
                    repository.findById(accountId).orElseThrow(), remoteAddress, userAgent, now, false);
        } finally {
            Arrays.fill(suppliedPassword, '\0');
        }
    }

    public IssuedSession login(
            String username,
            char[] password,
            String totpCode,
            String remoteAddress,
            String userAgent) {
        char[] suppliedPassword = password == null ? new char[0] : password;
        try {
        String normalizedUsername = SqliteAuthRepository.normalize(username);
        String addressKey = "address|" + String.valueOf(remoteAddress);
        String identityKey = "identity|" + String.valueOf(remoteAddress) + '|' + normalizedUsername;
        if (!rateLimiter.tryAcquire(addressKey) || !rateLimiter.tryAcquire(identityKey)) {
            Arrays.fill(suppliedPassword, '\0');
            throw new AuthenticationException("rate_limited", "too many login attempts");
        }
        Optional<AccountRecord> found = repository.findByUsername(username);
        boolean passwordShapeValid = suppliedPassword.length >= 12 && suppliedPassword.length <= 1_024;
        char[] passwordForHash = passwordShapeValid
                ? suppliedPassword
                : DUMMY_PASSWORD.toCharArray();
        String hashForVerification = found.map(AccountRecord::passwordHash).orElse(dummyPasswordHash);
        boolean validPassword = false;
        try {
            boolean hashMatches = verifyPasswordHash(passwordForHash, hashForVerification);
            validPassword = passwordShapeValid
                    && hashMatches
                    && found.isPresent()
                    && !found.get().disabled();
        } finally {
            Arrays.fill(suppliedPassword, '\0');
            if (passwordForHash != suppliedPassword) {
                Arrays.fill(passwordForHash, '\0');
            }
        }
        if (!validPassword || found.isEmpty()) {
            throw new AuthenticationException("invalid_credentials", "invalid username or credentials");
        }
        AccountRecord account = found.get();
        boolean secondFactorVerified = false;
        if (account.totpEnabled()) {
            SecondFactorResult result = verifyAccountSecondFactor(account, totpCode, true);
            if (result == SecondFactorResult.NONE) {
                throw new AuthenticationException("invalid_credentials", "invalid username or credentials");
            }
            secondFactorVerified = result == SecondFactorResult.TOTP;
        }
        rateLimiter.releaseLast(addressKey);
        rateLimiter.reset(identityKey);
        Instant now = clock.instant();
        repository.recordLogin(account.id(), now);
        return issueSession(account, remoteAddress, userAgent, now, secondFactorVerified);
        } finally {
            Arrays.fill(suppliedPassword, '\0');
        }
    }

    public Optional<AuthenticatedPrincipal> authenticate(String rawToken) {
        if (rawToken == null || rawToken.length() < 20 || rawToken.length() > 256) {
            return Optional.empty();
        }
        Instant now = clock.instant();
        return repository.findSessionByTokenHash(SecureTokens.sha256(rawToken)).flatMap(session -> {
            if (session.revokedAt() != null || !now.isBefore(session.expiresAt())
                    || !now.isBefore(session.lastSeenAt().plus(configuration.idleSessionTimeout()))) {
                return Optional.empty();
            }
            AccountRecord account = repository.findById(session.accountId()).orElse(null);
            if (account == null || account.disabled()) {
                return Optional.empty();
            }
            if (session.lastSeenAt().plus(SESSION_TOUCH_INTERVAL).isBefore(now)) {
                repository.touchSession(session.id(), now);
            }
            return Optional.of(new AuthenticatedPrincipal(
                    account.id(),
                    session.id(),
                    account.username(),
                    account.role(),
                    session.totpVerified(),
                    session.authenticatedAt(),
                    session.expiresAt()));
        });
    }

    public boolean verifyCsrf(String rawSessionToken, String csrfToken) {
        if (rawSessionToken == null || csrfToken == null || csrfToken.length() > 256) {
            return false;
        }
        return repository.findSessionByTokenHash(SecureTokens.sha256(rawSessionToken))
                .map(session -> SecureTokens.constantTimeEquals(
                        session.csrfHash(), SecureTokens.sha256(csrfToken)))
                .orElse(false);
    }

    public boolean recentlyAuthenticated(AuthenticatedPrincipal principal) {
        return principal.authenticatedAt()
                .plus(configuration.recentAuthenticationWindow())
                .isAfter(clock.instant());
    }

    public boolean verifySecondFactor(AuthenticatedPrincipal principal, String suppliedCode) {
        AccountRecord account = repository.findById(principal.accountId()).orElse(null);
        if (account == null || !account.totpEnabled() || account.encryptedTotpSecret() == null) {
            return false;
        }
        return verifyAccountSecondFactor(account, suppliedCode, false) == SecondFactorResult.TOTP;
    }

    public TotpEnrollment beginTotpEnrollment(AuthenticatedPrincipal principal, char[] password) {
        char[] suppliedPassword = password == null ? new char[0] : password;
        String limiterKey = "sensitive|" + principal.sessionId();
        try {
        requireSensitiveAttempt(limiterKey);
        AccountRecord account = requireActiveAccount(principal);
        if (account.totpEnabled()) {
            // Enrollment is not a reauthentication endpoint. In particular, a stolen session
            // plus the password must not refresh a previously TOTP-verified session without a
            // current second factor.
            throw new AuthenticationException("totp_already_enabled", "TOTP is already enabled");
        }
        verifyPassword(account, suppliedPassword);
        repository.markReauthenticated(principal.sessionId(), clock.instant());
        rateLimiter.reset(limiterKey);
        byte[] secret = SecureTokens.randomBytes(20);
        Instant expiresAt = clock.instant().plus(TOTP_ENROLLMENT_LIFETIME);
        PendingTotpEnrollment previous = pendingTotp.put(
                account.id(), new PendingTotpEnrollment(secret, expiresAt));
        if (previous != null) {
            previous.destroy();
        }
        String encodedSecret = totpService.base32Secret(secret);
        String label = urlEncode("XFEServerManager:" + account.username());
        String issuer = urlEncode("XFEServerManager");
        String uri = "otpauth://totp/" + label + "?secret=" + encodedSecret
                + "&issuer=" + issuer + "&algorithm=SHA1&digits=6&period=30";
        return new TotpEnrollment(encodedSecret, uri, expiresAt);
        } finally {
            Arrays.fill(suppliedPassword, '\0');
        }
    }

    /** Confirms enrollment and returns one-time recovery codes. */
    public List<String> confirmTotpEnrollment(
            AuthenticatedPrincipal principal, String suppliedCode) {
        AccountRecord account = requireActiveAccount(principal);
        String limiterKey = secondFactorLimiterKey(account.id());
        requireSecondFactorAttempt(limiterKey);
        PendingTotpEnrollment enrollment = pendingTotp.get(account.id());
        if (enrollment == null || !clock.instant().isBefore(enrollment.expiresAt())) {
            PendingTotpEnrollment removed = pendingTotp.remove(account.id());
            if (removed != null) {
                removed.destroy();
            }
            throw new AuthenticationException("totp_enrollment_expired", "TOTP enrollment has expired");
        }
        var acceptedCounter = totpService.matchingCounter(enrollment.secret(), suppliedCode);
        if (acceptedCounter.isEmpty()) {
            throw new AuthenticationException("invalid_totp", "TOTP code is invalid");
        }
        if (!pendingTotp.remove(account.id(), enrollment)) {
            throw new AuthenticationException(
                    "totp_enrollment_expired", "TOTP enrollment was replaced or has expired");
        }
        List<String> recoveryCodes = new ArrayList<>(RECOVERY_CODE_COUNT);
        List<byte[]> recoveryHashes = new ArrayList<>(RECOVERY_CODE_COUNT);
        try {
            for (int index = 0; index < RECOVERY_CODE_COUNT; index++) {
                String recovery = SecureTokens.randomUrlToken(16);
                recoveryCodes.add(recovery);
                recoveryHashes.add(SecureTokens.sha256(normalizeRecoveryCode(recovery)));
            }
            Instant now = clock.instant();
            byte[] aad = account.id().toString().getBytes(StandardCharsets.UTF_8);
            byte[] encrypted = secretBox.encrypt(enrollment.secret(), aad);
            repository.enableTotpWithRecoveryCodes(
                    account.id(),
                    encrypted,
                    acceptedCounter.getAsLong(),
                    recoveryHashes,
                    principal.sessionId(),
                    now);
            secondFactorRateLimiter.reset(limiterKey);
            return List.copyOf(recoveryCodes);
        } finally {
            enrollment.destroy();
        }
    }

    public void reauthenticate(
            AuthenticatedPrincipal principal, char[] password, String secondFactorCode) {
        char[] suppliedPassword = password == null ? new char[0] : password;
        String limiterKey = "sensitive|" + principal.sessionId();
        try {
        requireSensitiveAttempt(limiterKey);
        AccountRecord account = requireActiveAccount(principal);
        verifyPassword(account, suppliedPassword);
        if (account.totpEnabled()) {
            if (!reauthenticateSecondFactor(account, principal.sessionId(), secondFactorCode)) {
                throw new AuthenticationException("invalid_credentials", "invalid username or credentials");
            }
        } else {
            repository.markReauthenticated(principal.sessionId(), clock.instant());
        }
        rateLimiter.reset(limiterKey);
        } finally {
            Arrays.fill(suppliedPassword, '\0');
        }
    }

    /** Refreshes a live session with its bound authenticator; it never revives an expired session. */
    public void reauthenticateWithTotp(AuthenticatedPrincipal principal, String secondFactorCode) {
        String limiterKey = "sensitive|" + principal.sessionId();
        requireSensitiveAttempt(limiterKey);
        AccountRecord account = requireActiveAccount(principal);
        if (!account.totpEnabled()
                || !reauthenticateSecondFactor(account, principal.sessionId(), secondFactorCode)) {
            throw new AuthenticationException("invalid_credentials", "invalid TOTP or recovery code");
        }
        rateLimiter.reset(limiterKey);
    }

    /** Password-only accounts do not need to enroll a second factor to use their capabilities. */
    public boolean hasRequiredSecondFactor(AuthenticatedPrincipal principal) {
        return !requireActiveAccount(principal).totpEnabled() || principal.secondFactorVerified();
    }

    public void disableTotp(AuthenticatedPrincipal principal, char[] password, String secondFactorCode) {
        char[] suppliedPassword = password == null ? new char[0] : password;
        String limiterKey = "sensitive|" + principal.sessionId();
        try {
            requireSensitiveAttempt(limiterKey);
            AccountRecord account = requireActiveAccount(principal);
            verifyPassword(account, suppliedPassword);
            if (!account.totpEnabled()) {
                throw new AuthenticationException("totp_not_enabled", "two-factor authentication is not enabled");
            }
            if (verifyAccountSecondFactor(account, secondFactorCode, true) == SecondFactorResult.NONE) {
                throw new AuthenticationException("invalid_credentials", "invalid TOTP or recovery code");
            }
            repository.disableTotp(account.id(), account.encryptedTotpSecret(), principal.sessionId(), clock.instant());
            PendingTotpEnrollment pending = pendingTotp.remove(account.id());
            if (pending != null) pending.destroy();
            rateLimiter.reset(limiterKey);
        } finally {
            Arrays.fill(suppliedPassword, '\0');
        }
    }

    public boolean isTotpEnabled(AuthenticatedPrincipal principal) {
        return repository.findById(principal.accountId())
                .filter(account -> !account.disabled())
                .map(AccountRecord::totpEnabled)
                .orElse(false);
    }

    public String csrfToken(String rawSessionToken) {
        return SecureTokens.deriveCsrfToken(rawSessionToken);
    }

    public boolean setupRequired() {
        return repository.countOwners() == 0;
    }

    public List<AccountView> accounts(AuthenticatedPrincipal principal) {
        requireOwner(principal, false);
        return repository.listAccounts().stream().map(AuthenticationService::accountView).toList();
    }

    public AccountView account(AuthenticatedPrincipal principal, UUID accountId) {
        requireOwner(principal, false);
        return accountView(repository.findById(Objects.requireNonNull(accountId, "accountId"))
                .orElseThrow(() -> new java.util.NoSuchElementException("account does not exist")));
    }

    public synchronized AccountView createAccount(
            AuthenticatedPrincipal principal, String username, char[] password, Role role) {
        char[] suppliedPassword = password == null ? new char[0] : password;
        try {
            requireOwner(principal, true);
            validateUsername(username);
            Objects.requireNonNull(role, "role");
            if (suppliedPassword.length < 12 || suppliedPassword.length > 1_024) {
                throw new AuthenticationException(
                        "invalid_password", "password must contain 12 to 1024 characters");
            }
            if (repository.countAccounts() >= MAXIMUM_MANAGEMENT_ACCOUNTS) {
                throw new AccountConflictException("management account limit reached");
            }
            if (repository.findByUsername(username).isPresent()) {
                throw new AccountConflictException("username is already in use");
            }
            String passwordHash;
            acquirePasswordSlot();
            try {
                passwordHash = passwordHasher.hash(suppliedPassword);
            } finally {
                passwordSlots.release();
            }
            Instant now = clock.instant();
            AccountRecord account = new AccountRecord(
                    UUID.randomUUID(),
                    username.strip(),
                    SqliteAuthRepository.normalize(username),
                    passwordHash,
                    role,
                    null,
                    false,
                    false,
                    now,
                    now,
                    null);
            // Recheck owner authority in the same transaction as the insert. Password hashing can
            // take long enough for another owner to revoke this account after the first check.
            repository.createAccountAsOwner(principal.accountId(), account);
            return accountView(account);
        } finally {
            Arrays.fill(suppliedPassword, '\0');
        }
    }

    public AccountView updateAccount(
            AuthenticatedPrincipal principal,
            UUID accountId,
            Role role,
            Boolean disabled) {
        requireOwner(principal, true);
        if (role == null && disabled == null) {
            throw new IllegalArgumentException("role or disabled must be supplied");
        }
        if (principal.accountId().equals(accountId)
                && (Boolean.TRUE.equals(disabled) || (role != null && role != Role.OWNER))) {
            throw new AccountConflictException(
                    "another owner must disable or demote the current account");
        }
        return accountView(repository.updateAccountAsOwner(
                principal.accountId(), Objects.requireNonNull(accountId, "accountId"),
                role, disabled, clock.instant()));
    }

    public void deleteAccount(AuthenticatedPrincipal principal, UUID accountId) {
        requireOwner(principal, true);
        if (principal.accountId().equals(accountId)) {
            throw new AccountConflictException(
                    "another owner must delete the current account");
        }
        repository.deleteAccountAsOwner(
                principal.accountId(), Objects.requireNonNull(accountId, "accountId"));
    }

    public void logout(AuthenticatedPrincipal principal) {
        repository.revokeSession(principal.sessionId(), clock.instant());
    }

    public List<SessionView> sessions(AuthenticatedPrincipal principal) {
        requireActiveAccount(principal);
        Instant now = clock.instant();
        return repository.listSessions(principal.accountId()).stream()
                .filter(session -> now.isBefore(session.expiresAt()))
                .filter(session -> now.isBefore(
                        session.lastSeenAt().plus(configuration.idleSessionTimeout())))
                .map(session -> new SessionView(
                        session.id(),
                        session.createdAt(),
                        session.lastSeenAt(),
                        session.expiresAt(),
                        session.id().equals(principal.sessionId()),
                        redactedSource(session.remoteAddress())))
                .toList();
    }

    /** Revokes only a session owned by the authenticated account; absent sessions are a no-op. */
    public void revokeSession(AuthenticatedPrincipal principal, UUID sessionId) {
        requireActiveAccount(principal);
        repository.revokeSession(principal.accountId(), Objects.requireNonNull(sessionId), clock.instant());
    }

    private IssuedSession issueSession(
            AccountRecord account,
            String remoteAddress,
            String userAgent,
            Instant now,
            boolean secondFactorVerified) {
        String rawToken = SecureTokens.randomUrlToken(32);
        String csrfToken = SecureTokens.deriveCsrfToken(rawToken);
        UUID sessionId = UUID.randomUUID();
        Instant expiresAt = now.plus(configuration.absoluteSessionTimeout());
        repository.createSession(
                new SessionRecord(
                        sessionId,
                        account.id(),
                        SecureTokens.sha256(rawToken),
                        SecureTokens.sha256(csrfToken),
                        now,
                        now,
                        now,
                        secondFactorVerified,
                        expiresAt,
                        null),
                remoteAddress,
                userAgent == null ? null : SecureTokens.sha256(userAgent));
        repository.pruneAccountSessions(
                account.id(),
                MAXIMUM_ACTIVE_SESSIONS_PER_ACCOUNT,
                now,
                now.minus(configuration.idleSessionTimeout()));
        return new IssuedSession(
                new AuthenticatedPrincipal(
                        account.id(),
                        sessionId,
                        account.username(),
                        account.role(),
                        secondFactorVerified,
                        now,
                        expiresAt),
                rawToken,
                csrfToken,
                expiresAt);
    }

    private static void validateUsername(String username) {
        if (username == null || !username.matches("[A-Za-z0-9_.-]{3,32}")) {
            throw new AuthenticationException(
                    "invalid_username", "username must contain 3-32 safe ASCII characters");
        }
    }

    private AccountRecord requireActiveAccount(AuthenticatedPrincipal principal) {
        return repository.findById(principal.accountId())
                .filter(account -> !account.disabled())
                .orElseThrow(() -> new AuthenticationException(
                        "invalid_session", "the account is unavailable"));
    }

    private AccountRecord requireOwner(
            AuthenticatedPrincipal principal, boolean requireRecentStrongAuthentication) {
        AccountRecord account = requireActiveAccount(Objects.requireNonNull(principal, "principal"));
        if (account.role() != Role.OWNER || principal.role() != Role.OWNER) {
            throw new SecurityException("only an owner may manage accounts");
        }
        if (requireRecentStrongAuthentication
                && ((account.totpEnabled() && !principal.secondFactorVerified())
                    || !recentlyAuthenticated(principal))) {
            throw new SecurityException(
                    "account changes require recent authentication and TOTP verification when enabled");
        }
        return account;
    }

    private static AccountView accountView(AccountRecord account) {
        return new AccountView(
                account.id(),
                account.username(),
                account.role().wireName(),
                account.totpEnabled(),
                account.disabled(),
                account.createdAt(),
                account.updatedAt(),
                account.lastLoginAt());
    }

    private void verifyPassword(AccountRecord account, char[] password) {
        char[] supplied = password == null ? new char[0] : password;
        boolean shapeValid = supplied.length >= 12 && supplied.length <= 1_024;
        char[] candidate = shapeValid ? supplied : DUMMY_PASSWORD.toCharArray();
        try {
            if (!verifyPasswordHash(candidate, account.passwordHash()) || !shapeValid) {
                throw new AuthenticationException("invalid_credentials", "invalid username or credentials");
            }
        } finally {
            Arrays.fill(supplied, '\0');
            if (candidate != supplied) {
                Arrays.fill(candidate, '\0');
            }
        }
    }

    private boolean verifyPasswordHash(char[] password, String encodedHash) {
        acquirePasswordSlot();
        try {
            return passwordHasher.verify(password, encodedHash);
        } finally {
            passwordSlots.release();
        }
    }

    private void acquirePasswordSlot() {
        if (!passwordSlots.tryAcquire()) {
            throw new AuthenticationException(
                    "rate_limited", "too many password computations are in progress");
        }
    }

    private void requireSensitiveAttempt(String limiterKey) {
        if (!rateLimiter.tryAcquire(limiterKey)) {
            throw new AuthenticationException(
                    "rate_limited", "too many sensitive authentication attempts");
        }
    }

    private void requireSecondFactorAttempt(String limiterKey) {
        if (!secondFactorRateLimiter.tryAcquire(limiterKey)) {
            throw new AuthenticationException(
                    "rate_limited",
                    "too many two-factor verification attempts; wait 10 minutes before trying again");
        }
    }

    private static String secondFactorLimiterKey(UUID accountId) {
        return "second-factor|" + accountId;
    }

    private SecondFactorResult verifyAccountSecondFactor(
            AccountRecord account, String suppliedCode, boolean allowRecoveryCode) {
        if (account.encryptedTotpSecret() == null) {
            return SecondFactorResult.NONE;
        }
        String limiterKey = secondFactorLimiterKey(account.id());
        requireSecondFactorAttempt(limiterKey);
        byte[] secret = secretBox.decrypt(
                account.encryptedTotpSecret(),
                account.id().toString().getBytes(StandardCharsets.UTF_8));
        try {
            var matchingCounter = totpService.matchingCounter(secret, suppliedCode);
            if (matchingCounter.isPresent()
                    && repository.consumeTotpCounter(
                            account.id(), matchingCounter.getAsLong(), clock.instant())) {
                secondFactorRateLimiter.reset(limiterKey);
                return SecondFactorResult.TOTP;
            }
        } finally {
            Arrays.fill(secret, (byte) 0);
        }
        boolean recovered = allowRecoveryCode
                && suppliedCode != null
                && repository.consumeRecoveryCode(
                        account.id(),
                        SecureTokens.sha256(normalizeRecoveryCode(suppliedCode)),
                        clock.instant());
        if (recovered) secondFactorRateLimiter.reset(limiterKey);
        return recovered ? SecondFactorResult.RECOVERY : SecondFactorResult.NONE;
    }

    private boolean reauthenticateSecondFactor(
            AccountRecord account, UUID sessionId, String suppliedCode) {
        if (account.encryptedTotpSecret() == null) {
            return false;
        }
        String limiterKey = secondFactorLimiterKey(account.id());
        requireSecondFactorAttempt(limiterKey);
        Instant now = clock.instant();
        byte[] secret = secretBox.decrypt(
                account.encryptedTotpSecret(),
                account.id().toString().getBytes(StandardCharsets.UTF_8));
        try {
            var counter = totpService.matchingCounter(secret, suppliedCode);
            if (counter.isPresent()) {
                boolean accepted = repository.consumeTotpCounterAndMarkSession(
                        account.id(), sessionId, counter.getAsLong(), now);
                if (accepted) secondFactorRateLimiter.reset(limiterKey);
                return accepted;
            }
        } finally {
            Arrays.fill(secret, (byte) 0);
        }
        boolean recovered = suppliedCode != null && repository.consumeRecoveryCodeAndMarkSession(
                account.id(),
                sessionId,
                SecureTokens.sha256(normalizeRecoveryCode(suppliedCode)),
                now);
        if (recovered) secondFactorRateLimiter.reset(limiterKey);
        return recovered;
    }

    private static String normalizeRecoveryCode(String code) {
        return code == null ? "" : code.strip().toLowerCase(Locale.ROOT);
    }

    private static String urlEncode(String value) {
        return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20");
    }

    private static String redactedSource(String address) {
        if (address == null || address.isBlank()) {
            return "unknown";
        }
        String normalized = address.strip().toLowerCase(Locale.ROOT);
        return normalized.equals("::1")
                        || normalized.equals("0:0:0:0:0:0:0:1")
                        || normalized.startsWith("127.")
                ? "loopback"
                : "remote";
    }

    public record TotpEnrollment(String secret, String provisioningUri, Instant expiresAt) { }

    public record SessionView(
            UUID id,
            Instant createdAt,
            Instant lastSeenAt,
            Instant expiresAt,
            boolean current,
            String source) { }

    public record AccountView(
            UUID id,
            String username,
            String role,
            boolean totpEnabled,
            boolean disabled,
            Instant createdAt,
            Instant updatedAt,
            Instant lastLoginAt) { }

    private enum SecondFactorResult {
        NONE,
        TOTP,
        RECOVERY
    }

    private static final class PendingTotpEnrollment {
        private final byte[] secret;
        private final Instant expiresAt;

        private PendingTotpEnrollment(byte[] secret, Instant expiresAt) {
            this.secret = secret.clone();
            this.expiresAt = expiresAt;
        }

        private byte[] secret() {
            return secret;
        }

        private Instant expiresAt() {
            return expiresAt;
        }

        private void destroy() {
            Arrays.fill(secret, (byte) 0);
        }
    }

    public static final class AuthenticationException extends RuntimeException {
        private static final long serialVersionUID = 1L;
        private final String code;

        public AuthenticationException(String code, String message) {
            super(message);
            this.code = code;
        }

        public String code() {
            return code;
        }
    }

}
