// ── Admin · Users: the core half of /admin/users/:id ───────────────────────
//
// `getUser` lived in usersShard.controller.js until Phase 2 PR 4, purely because
// the detail page it backs is mostly shard panels. MODULE_SYSTEM.md §1.9 called
// that out as core semantics that ended up in the UO controller by proximity, and
// it moved back to admin.controller.js — the shard panels around it are now an
// extension slot, so this handler has to stand on its own when they leave.
//
// Point the DB at a closed port BEFORE requiring anything that builds the pool,
// so any stray query fails fast instead of hanging the runner.
process.env.DB_HOST = '127.0.0.1'
process.env.DB_PORT = '59999'

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

const ctrl = require('../src/router/v1/admin/admin.controller')
const users = require('../src/model/users/users.model')
const db = require('../src/utils/db')

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

function mockRes() {
  return {
    statusCode: 200,
    body: null,
    status(c) {
      this.statusCode = c
      return this
    },
    json(b) {
      this.body = b
      return this
    },
  }
}

const originalGetById = users.getById
afterEach(() => {
  users.getById = originalGetById
})

test('getUser returns the sanitized user row', async () => {
  users.getById = async () => ({ id: 7, username: 'bob', role: 'player', status: 'active' })
  const res = mockRes()
  await ctrl.getUser({ params: { id: '7' } }, res)
  assert.equal(res.statusCode, 200)
  assert.equal(res.body.username, 'bob')
})

test('getUser returns 404 when the user does not exist', async () => {
  users.getById = async () => null
  const res = mockRes()
  await ctrl.getUser({ params: { id: '404' } }, res)
  assert.equal(res.statusCode, 404)
})

test('getUser 500s rather than throwing when the model fails', async () => {
  users.getById = async () => {
    throw new Error('pool down')
  }
  const res = mockRes()
  await ctrl.getUser({ params: { id: '7' } }, res)
  assert.equal(res.statusCode, 500)
})
