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

const router = Router()
export default router

class PostApiRoute extends BaseApi {
  async echoProperties(req: Request, res: Response): Promise<void> {
    const { headers, query, method } = req
    const body = await this.readRequestBuffer(req)
    const bodyStr = body.toString('utf8')

    // Try to parse as JSON if content-type is application/json
    let parsedBody = bodyStr
    if (headers['content-type']?.includes('application/json')) {
      try {
        parsedBody = JSON.parse(bodyStr)
      } catch {
        // If parsing fails, keep as string
        parsedBody = bodyStr
      }
    }

    res.send({ headers, query, method, body: parsedBody })
  }
}
const api = new PostApiRoute()
api.setCors(router)
const checkCorsFn = api._processCors
router.post('/', cors(checkCorsFn), api.echoProperties.bind(api))
