import { describe, it, expect, vi, beforeEach } from 'vitest'

// Test that the three Helcim admin endpoints require admin auth.
// We verify the handler files import/call requireAdmin by checking
// the module source, and we test that requireAdmin rejects properly
// via the existing auth.test.js infrastructure.

// We test the schema + handler wiring by reading the file and
// confirming requireAdmin is the first call in the handler.

import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'

const serverDir = resolve(import.meta.dirname, '../../../server/api/helcim')

describe('Helcim admin endpoint auth guards', () => {
  const files = [
    'create-plan.post.js',
    'plans.get.js',
    'subscriptions.get.js'
  ]

  for (const file of files) {
    describe(file, () => {
      const source = readFileSync(resolve(serverDir, file), 'utf-8')

      it('calls requireAdmin', () => {
        expect(source).toContain('requireAdmin(event)')
      })

      it('calls requireAdmin before any business logic', () => {
        const adminIndex = source.indexOf('requireAdmin(event)')
        const readBodyIndex = source.indexOf('readBody(event)')
        const validateBodyIndex = source.indexOf('validateBody(event')
        const fetchIndex = source.indexOf('fetch(')

        expect(adminIndex).toBeGreaterThan(-1)

        // requireAdmin must come before readBody/validateBody/fetch
        if (readBodyIndex > -1) {
          expect(adminIndex).toBeLessThan(readBodyIndex)
        }
        if (validateBodyIndex > -1) {
          expect(adminIndex).toBeLessThan(validateBodyIndex)
        }
        if (fetchIndex > -1) {
          expect(adminIndex).toBeLessThan(fetchIndex)
        }
      })
    })
  }
})
