// Mobile refresh-token store. Thin logic layer over mobileSessions.db — mirrors
// the users model split (.db = SQL, .model = the API the rest of the app calls).
// The refresh token itself is opaque and lives client-side; only its hash is
// persisted (hashing is done by the session service so caller + store agree).

const db = require('./mobileSessions.db')

// Persist a newly issued refresh token (by hash). Returns the row id.
async function store({ userId, tokenHash, deviceHash, deviceName, userAgent, expiresAt }) {
  return db.insert({ userId, tokenHash, deviceHash, deviceName, userAgent, expiresAt })
}

// List a user's active sessions (one per live device) for the Active Devices UI.
async function listActiveForUser(userId) {
  return db.listActiveForUser(userId)
}

// Revoke one of a user's own sessions by row id. Returns rows changed (0 if it
// wasn't theirs / already gone — callers treat this idempotently).
async function revokeByIdForUser(id, userId) {
  return db.revokeByIdForUser(id, userId)
}

// Return the stored row for a still-valid (unrevoked, unexpired) token, else null.
async function findValidByHash(tokenHash) {
  return db.findValidByHash(tokenHash)
}

// Revoke one refresh token (logout / rotation). Returns rows changed (0 if it was
// already gone/revoked — callers treat this idempotently).
async function revokeByHash(tokenHash) {
  return db.revokeByHash(tokenHash)
}

// Revoke all of a user's refresh tokens (logout everywhere).
async function revokeAllForUser(userId) {
  return db.revokeAllForUser(userId)
}

// Drop expired/revoked rows.
async function pruneExpired() {
  return db.pruneExpired()
}

module.exports = {
  store,
  listActiveForUser,
  revokeByIdForUser,
  findValidByHash,
  revokeByHash,
  revokeAllForUser,
  pruneExpired,
}
