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, after, beforeEach } = require('node:test')
const assert = require('node:assert/strict')

const emailConfig = require('../src/model/emailConfig/emailConfig.model')
const emailDb = require('../src/model/emailConfig/emailConfig.db')
const secretBox = require('../src/utils/secretBox')
const db = require('../src/utils/db')

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

// In-memory stand-in for the singleton row so the model never touches MariaDB.
let store
beforeEach(() => {
  store = null
  emailDb.get = async () => store
  emailDb.upsert = async (fields) => {
    store = { ...(store || { id: 1 }), ...fields }
    return store
  }
})

test('save encrypts the refresh token (ciphertext at rest, decryptable)', async () => {
  await emailConfig.save({ senderEmail: 'me@gmail.com', refreshToken: 'refresh-abc', enabled: true })
  assert.ok(store.refresh_token_enc)
  assert.notEqual(store.refresh_token_enc, 'refresh-abc')
  assert.equal(secretBox.decrypt(store.refresh_token_enc), 'refresh-abc')

  const withSecret = await emailConfig.getWithSecret()
  assert.equal(withSecret.refreshToken, 'refresh-abc')
})

test('getSafe never leaks the refresh token', async () => {
  await emailConfig.save({ senderEmail: 'me@gmail.com', refreshToken: 'refresh-abc', enabled: true })
  const safe = await emailConfig.getSafe()
  assert.equal(safe.hasRefreshToken, true)
  assert.equal(safe.senderEmail, 'me@gmail.com')
  assert.equal('refreshToken' in safe, false)
  assert.equal('refresh_token_enc' in safe, false)
})

test('blank refresh token on save leaves the existing one unchanged', async () => {
  await emailConfig.save({ senderEmail: 'me@gmail.com', refreshToken: 'refresh-abc', enabled: true })
  const cipherBefore = store.refresh_token_enc

  await emailConfig.save({ senderName: 'UOMysticmoon' }) // no refreshToken
  assert.equal(store.refresh_token_enc, cipherBefore) // untouched
  assert.equal(store.sender_name, 'UOMysticmoon')
  assert.equal(secretBox.decrypt(store.refresh_token_enc), 'refresh-abc')
})

test('disconnect clears the credential and disables sending', async () => {
  await emailConfig.save({ senderEmail: 'me@gmail.com', refreshToken: 'refresh-abc', enabled: true })
  const safe = await emailConfig.disconnect(7)
  assert.equal(store.refresh_token_enc, null)
  assert.equal(store.enabled, 0)
  assert.equal(safe.hasRefreshToken, false)
  assert.equal(safe.status, 'unconfigured')
})

test('getSafe returns unconfigured defaults when no row exists', async () => {
  const safe = await emailConfig.getSafe()
  assert.equal(safe.enabled, false)
  assert.equal(safe.hasRefreshToken, false)
  assert.equal(safe.status, 'unconfigured')
  assert.equal(safe.senderEmail, null)
})
