// Point the DB at a closed port BEFORE requiring the model (it builds the pool).
// The .db layer is monkeypatched so no query runs; db.close() releases the pool.
process.env.DB_HOST = '127.0.0.1'
process.env.DB_PORT = '59999'

const { test, after, beforeEach, afterEach } = require('node:test')
const assert = require('node:assert/strict')
const bcrypt = require('bcryptjs')

// Unit-test the recovery-code model. Invariants a regression must not break:
//   - generation returns the requested count of human-formatted codes and REPLACES
//     any prior set (delete-then-insert), storing only bcrypt hashes;
//   - a code verifies regardless of case/dash formatting, and only once (single use);
//   - a wrong code never consumes anything.
const model = require('../src/model/recoveryCodes/recoveryCodes.model')
const codesDb = require('../src/model/recoveryCodes/recoveryCodes.db')
const db = require('../src/utils/db')

after(() => db.close())

const orig = {}
beforeEach(() => {
  for (const name of ['insertMany', 'listUnusedForUser', 'countUnusedForUser', 'markUsed', 'deleteAllForUser']) {
    orig[name] = codesDb[name]
  }
})
afterEach(() => {
  for (const name of Object.keys(orig)) codesDb[name] = orig[name]
  for (const k of Object.keys(orig)) delete orig[k]
})

test('normalize strips separators/whitespace and uppercases', () => {
  assert.equal(model.normalize('abcde-fghij'), 'ABCDEFGHIJ')
  assert.equal(model.normalize('  ab cd '), 'ABCD')
  assert.equal(model.normalize(null), '')
})

test('generateForUser returns the requested count, replaces the old set, and stores only hashes', async () => {
  let deleted = null
  let inserted = null
  codesDb.deleteAllForUser = async (id) => { deleted = id }
  codesDb.insertMany = async (id, hashes) => { inserted = { id, hashes }; return hashes.length }

  const codes = await model.generateForUser(42, 5)

  assert.equal(codes.length, 5)
  assert.equal(deleted, 42, 'old codes are cleared first')
  assert.equal(inserted.id, 42)
  assert.equal(inserted.hashes.length, 5)
  // Nothing stored in the clear: every persisted value is a bcrypt hash, and it
  // is NOT the code itself.
  for (let i = 0; i < 5; i++) {
    assert.match(inserted.hashes[i], /^\$2[aby]\$/)
    assert.notEqual(inserted.hashes[i], model.normalize(codes[i]))
  }
  // Each displayed code carries a separator for readability.
  assert.ok(codes.every((c) => c.includes('-')))
})

test('consumeForUser accepts a formatted code once, then never again', async () => {
  const plainCanonical = 'ABCDE23456'
  const hash = await bcrypt.hash(plainCanonical, 10)
  const rows = [{ id: 1, code_hash: await bcrypt.hash('OTHER12345', 10) }, { id: 2, code_hash: hash }]
  const marked = []
  codesDb.listUnusedForUser = async () => rows.filter((r) => !marked.includes(r.id))
  codesDb.markUsed = async (id) => { marked.push(id); return 1 }

  // Case/format-insensitive: the user may type it lowercase with a dash.
  const ok = await model.consumeForUser(7, 'abcde-23456')
  assert.equal(ok, true)
  assert.deepEqual(marked, [2], 'the matching row was consumed')

  // Single use: the same code no longer verifies (its row is now used).
  const again = await model.consumeForUser(7, 'abcde-23456')
  assert.equal(again, false)
})

test('consumeForUser returns false for a wrong code and consumes nothing', async () => {
  const rows = [{ id: 1, code_hash: await bcrypt.hash('REALCODE99', 10) }]
  let markedCount = 0
  codesDb.listUnusedForUser = async () => rows
  codesDb.markUsed = async () => { markedCount++; return 1 }

  const ok = await model.consumeForUser(7, 'WRONGCODE0')
  assert.equal(ok, false)
  assert.equal(markedCount, 0)
})

test('consumeForUser is false for an empty input without touching the DB', async () => {
  let listed = false
  codesDb.listUnusedForUser = async () => { listed = true; return [] }
  const ok = await model.consumeForUser(7, '   ')
  assert.equal(ok, false)
  assert.equal(listed, false)
})
