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

const router = Router()
export default router

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

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

    // Decode Basic auth credentials
    const credentials = Buffer.from(authHeader.substring(6), 'base64').toString('utf8')
    const [username, password] = credentials.split(':')

    // Simple validation for test purposes
    if (username === 'testuser' && password === 'testpass') {
      res.setHeader('content-type', 'application/json')
      res.json({ authenticated: true, username })
    } else {
      res.setHeader('WWW-Authenticate', 'Basic realm="Test Realm"')
      res.status(401).json({ error: 'Invalid credentials' })
    }
  }
}

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