// Point the DB at a closed port BEFORE requiring anything that builds the pool —
// these cases reject at requireAuth (no session token) before any query runs.
process.env.DB_HOST = '127.0.0.1'
process.env.DB_PORT = '59999'

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

const { startApp } = require('./_helper')
const authRouter = require('../src/router/v1/auth')
const db = require('../src/utils/db')

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

// The push-notification self surface (/auth/me/devices*, /auth/me/notifications/*)
// must be mounted AND gated: an unauthenticated caller gets 401 on every route —
// never 404 (route missing) and never 200 (gate bypassed).
test('/auth/me push routes reject unauthenticated callers with 401', async () => {
  const app = await startApp((a) => a.use('/api/v1/auth', authRouter))
  try {
    const calls = [
      ['GET', '/api/v1/auth/me/devices'],
      ['POST', '/api/v1/auth/me/devices', { endpoint: 'https://ntfy.example.com/UPabc' }],
      ['DELETE', '/api/v1/auth/me/devices/1'],
      ['GET', '/api/v1/auth/me/notifications/streams'],
      ['GET', '/api/v1/auth/me/notifications/subscriptions'],
      ['PUT', '/api/v1/auth/me/notifications/subscriptions', { streams: ['news.post'] }],
    ]
    for (const [method, path, body] of calls) {
      const res = await fetch(app.url + path, {
        method,
        headers: body ? { 'Content-Type': 'application/json' } : {},
        body: body ? JSON.stringify(body) : undefined,
      })
      assert.equal(res.status, 401, `${method} ${path} should be 401, got ${res.status}`)
    }
  } finally {
    await app.close()
  }
})
