import { Router, Request, Response } from 'express'
import cors from 'cors'
import { BaseApi } from './BaseApi.js'

const router = Router()
export default router

class BearerAuthRoute extends BaseApi {
  async resource(req: Request, res: Response): Promise<void> {
    const authHeader = req.headers.authorization

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      res.setHeader('WWW-Authenticate', 'Bearer realm="Test Realm"')
      res.status(401).json({ error: 'Authentication required' })
      return
    }

    // Extract Bearer token
    const token = authHeader.substring(7)

    // Simple validation for test purposes
    if (token === 'test-token-123') {
      res.setHeader('content-type', 'application/json')
      res.json({ authenticated: true, token })
    } else {
      res.setHeader('WWW-Authenticate', 'Bearer realm="Test Realm"')
      res.status(401).json({ error: 'Invalid token' })
    }
  }
}

const api = new BearerAuthRoute()
api.setCors(router)
const checkCorsFn = api._processCors
router.get('/resource', cors(checkCorsFn), api.resource.bind(api))
