process.env.JWT_SECRET = process.env.JWT_SECRET || 'test-secret'
process.env.SECRET_ENC_KEY = process.env.SECRET_ENC_KEY || 'unit-test-enc-key'
process.env.DB_HOST = '127.0.0.1'
process.env.DB_PORT = '59999'

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

const ssoCtrl = require('../src/router/v1/auth/sso.controller')
const ssoState = require('../src/auth/ssoState')
const token = require('../src/auth/token')
// Modules whose methods we stub (exports are plain objects → mutable in-process).
const users = require('../src/model/users/users.model')
const activity = require('../src/model/activity/activity.model')
const authProviders = require('../src/model/authProviders/authProviders.model')
const userIdentities = require('../src/model/userIdentities/userIdentities.model')
const settings = require('../src/model/settings/settings.model')
const registry = require('../src/auth/providers/registry')
const totp = require('../src/utils/totp')
const db = require('../src/utils/db')

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

const GOOGLE_ROW = { id: 'google', kind: 'google', name: 'Google', enabled: 1, client_id: 'cid', client_secret_enc: 'enc' }
const PROFILE = { subject: 'sub-1', email: 'alice@example.com', name: 'Alice' }

let logged
beforeEach(() => {
  logged = []
  activity.log = async (evt) => { logged.push(evt) }
  authProviders.getWithSecret = async () => ({ ...GOOGLE_ROW })
  // Bypass real OAuth network calls: the provider just yields a fixed profile.
  registry.instantiate = () => ({ handleCallback: async () => ({ ...PROFILE }) })
  userIdentities.findByProviderSubject = async () => null
  userIdentities.link = async () => 1
  users.getById = async (id) => ({ id, username: 'alice', role: 'admin' })
  users.recordLogin = async () => {} // avoid the real DB on the success path
  // Default: registration closed, so login stays strictly link-only unless a
  // test opts into SSO sign-up.
  settings.getRegistrationMode = async () => 'disabled'
})

function mockRes() {
  return {
    statusCode: 200, redirectedTo: null, cookies: {}, cleared: [],
    status(c) { this.statusCode = c; return this },
    json(b) { this.body = b; return this },
    redirect(u) { this.redirectedTo = u; return this },
    cookie(n, v) { this.cookies[n] = v; return this },
    clearCookie(n) { this.cleared.push(n); return this },
  }
}

function makeReq(tx, { state, code = 'auth-code' } = {}) {
  return {
    params: { provider: 'google' },
    cookies: { [ssoState.TX_COOKIE]: tx.txToken },
    query: { state: state ?? tx.nonce, code },
    ip: '127.0.0.1', protocol: 'http', get: () => 'localhost', headers: {},
  }
}

test('linked identity → session cookie set, redirect to /admin, login logged', async () => {
  userIdentities.findByProviderSubject = async () => ({ user_id: 7 })
  const tx = ssoState.createTx({ provider: 'google', mode: 'login' })
  const res = mockRes()
  await ssoCtrl.callback(makeReq(tx), res)

  assert.ok(res.cookies[token.COOKIE_NAME], 'session cookie was set')
  assert.equal(res.redirectedTo, '/admin')
  assert.ok(res.cleared.includes(ssoState.TX_COOKIE), 'tx cookie cleared')
  assert.equal(logged.at(-1).action, 'auth.sso.login')
})

test('linked identity honors a safe returnTo', async () => {
  userIdentities.findByProviderSubject = async () => ({ user_id: 7 })
  const tx = ssoState.createTx({ provider: 'google', mode: 'login', returnTo: '/admin/posts' })
  const res = mockRes()
  await ssoCtrl.callback(makeReq(tx), res)
  assert.equal(res.redirectedTo, '/admin/posts')
})

test('UNLINKED identity → no session, redirect to not_linked (link-only policy)', async () => {
  userIdentities.findByProviderSubject = async () => null
  const tx = ssoState.createTx({ provider: 'google', mode: 'login' })
  const res = mockRes()
  await ssoCtrl.callback(makeReq(tx), res)

  assert.equal(res.cookies[token.COOKIE_NAME], undefined, 'no session cookie')
  assert.equal(res.redirectedTo, '/admin/login?sso_error=not_linked')
  assert.equal(logged.length, 0)
})

test('UNLINKED identity + SSO sign-up enabled → auto-provisions a player and logs in', async () => {
  settings.getRegistrationMode = async () => 'both'
  userIdentities.findByProviderSubject = async () => null
  let created = null
  users.createUser = async (args) => {
    created = args
    return { id: 42, username: args.username, role: 'player', status: 'active' }
  }
  let linkArgs = null
  userIdentities.link = async (args) => { linkArgs = args; return 1 }
  const tx = ssoState.createTx({ provider: 'google', mode: 'login' })
  const res = mockRes()
  await ssoCtrl.callback(makeReq(tx), res)

  assert.equal(created.role, 'player')
  assert.equal(created.email, 'alice@example.com')
  assert.equal(linkArgs.userId, 42)
  assert.ok(res.cookies[token.COOKIE_NAME], 'session cookie set for the new player')
  assert.equal(res.redirectedTo, '/admin')
  // Both the provision and the login are audited.
  assert.deepEqual(logged.map((e) => e.action), ['auth.sso.provision', 'auth.sso.login'])
})

test('UNLINKED identity from the player portal lands back in /account', async () => {
  settings.getRegistrationMode = async () => 'both'
  userIdentities.findByProviderSubject = async () => null
  users.createUser = async (args) => ({ id: 43, username: args.username, role: 'player', status: 'active' })
  const tx = ssoState.createTx({ provider: 'google', mode: 'login', returnTo: '/account' })
  const res = mockRes()
  await ssoCtrl.callback(makeReq(tx), res)
  assert.equal(res.redirectedTo, '/account')
})

test('link mode → identity linked to the acting user, redirect to account', async () => {
  let linkArgs = null
  userIdentities.link = async (args) => { linkArgs = args; return 1 }
  const tx = ssoState.createTx({ provider: 'google', mode: 'link', linkUserId: 5 })
  const res = mockRes()
  await ssoCtrl.callback(makeReq(tx), res)

  assert.deepEqual(linkArgs, { userId: 5, provider: 'google', subject: 'sub-1', email: 'alice@example.com' })
  assert.equal(res.redirectedTo, '/admin/account?linked=google')
  assert.equal(logged.at(-1).action, 'auth.sso.link')
  assert.equal(res.cookies[token.COOKIE_NAME], undefined, 'linking does not start a session')
})

test('link mode refuses an identity already owned by another user', async () => {
  userIdentities.findByProviderSubject = async () => ({ user_id: 999 })
  const tx = ssoState.createTx({ provider: 'google', mode: 'link', linkUserId: 5 })
  const res = mockRes()
  await ssoCtrl.callback(makeReq(tx), res)
  assert.equal(res.redirectedTo, '/admin/account?link_error=in_use')
})

test('bad state (CSRF) → rejected before any provider work', async () => {
  const tx = ssoState.createTx({ provider: 'google', mode: 'login' })
  const res = mockRes()
  await ssoCtrl.callback(makeReq(tx, { state: 'tampered-nonce' }), res)
  assert.equal(res.redirectedTo, '/admin/login?sso_error=bad_state')
  assert.equal(res.cookies[token.COOKIE_NAME], undefined)
})

// ── 2FA parity: SSO must not bypass TOTP (issue #31) ────────────────────────

test('linked account with TOTP → staged challenge, NO session, routed to TOTP', async () => {
  userIdentities.findByProviderSubject = async () => ({ user_id: 7 })
  users.getById = async (id) => ({ id, username: 'alice', role: 'admin', totp_enabled: 1 })
  const tx = ssoState.createTx({ provider: 'google', mode: 'login', returnTo: '/admin/posts' })
  const res = mockRes()
  await ssoCtrl.callback(makeReq(tx), res)

  assert.equal(res.cookies[token.COOKIE_NAME], undefined, 'no full session before 2FA')
  assert.ok(res.cookies[ssoState.TOTP_COOKIE], 'pending-TOTP cookie staged')
  assert.equal(res.redirectedTo, '/admin/login?sso_totp=1')
  assert.equal(logged.length, 0, 'login not logged until the second factor passes')
  // The staged cookie carries the resolved context and is not a usable session.
  const pending = ssoState.verifyTotpPending(res.cookies[ssoState.TOTP_COOKIE])
  assert.equal(pending.id, 7)
  assert.equal(pending.provider, 'google')
  assert.equal(pending.returnTo, '/admin/posts')
})

function makeTotpReq(pendingToken, code) {
  return {
    cookies: pendingToken ? { [ssoState.TOTP_COOKIE]: pendingToken } : {},
    body: { code },
    ip: '127.0.0.1', protocol: 'http', get: () => 'localhost', headers: {},
  }
}

test('finishSsoTotp: correct code → session issued, pending cookie cleared, login logged', async () => {
  users.getRawById = async (id) => ({ id, username: 'alice', role: 'admin', totp_enabled: 1, totp_secret: 'S' })
  totp.verifyCode = () => true
  const pending = ssoState.createTotpPending({ userId: 7, provider: 'google', authMethod: 'google', returnTo: '/admin/posts' })
  const res = mockRes()
  await ssoCtrl.finishSsoTotp(makeTotpReq(pending, '123456'), res)

  assert.ok(res.cookies[token.COOKIE_NAME], 'session cookie set after 2FA')
  assert.ok(res.cleared.includes(ssoState.TOTP_COOKIE), 'pending-TOTP cookie cleared')
  assert.equal(res.body.returnTo, '/admin/posts')
  assert.equal(res.body.user.id, 7)
  assert.equal(logged.at(-1).action, 'auth.sso.login')
  assert.equal(logged.at(-1).detail.totp, true)
})

test('finishSsoTotp: wrong code → 401, no session', async () => {
  users.getRawById = async (id) => ({ id, username: 'alice', role: 'admin', totp_enabled: 1, totp_secret: 'S' })
  totp.verifyCode = () => false
  const pending = ssoState.createTotpPending({ userId: 7, provider: 'google', authMethod: 'google' })
  const res = mockRes()
  await ssoCtrl.finishSsoTotp(makeTotpReq(pending, '000000'), res)

  assert.equal(res.statusCode, 401)
  assert.match(res.body.message, /Invalid verification code/)
  assert.equal(res.cookies[token.COOKIE_NAME], undefined)
})

test('finishSsoTotp: missing/expired pending cookie → 401 expired', async () => {
  const res = mockRes()
  await ssoCtrl.finishSsoTotp(makeTotpReq(null, '123456'), res)
  assert.equal(res.statusCode, 401)
  assert.match(res.body.message, /expired/i)
  assert.equal(res.cookies[token.COOKIE_NAME], undefined)
})

test('finishSsoTotp: a local /login/totp challenge is not accepted here', async () => {
  // A stage:'totp' token without kind:'sso_totp' must be rejected by this endpoint.
  const localChallenge = token.signTotpChallenge({ id: 7 })
  const res = mockRes()
  await ssoCtrl.finishSsoTotp(makeTotpReq(localChallenge, '123456'), res)
  assert.equal(res.statusCode, 401)
  assert.match(res.body.message, /expired/i)
})
