import { Router, Request, Response } from 'express'
import { BaseApi } from './BaseApi.js'
import cors from 'cors'
import { DataMock } from '@pawel-up/data-mock'

const router = Router()
export default router

class StreamRoute extends BaseApi {
  #mock = new DataMock()

  async index(req: Request, res: Response): Promise<void> {
    res.writeHead(200, {
      'Content-Type': 'text/plain; charset=UTF-8',
      'Transfer-Encoding': 'chunked',
    })
    this.#writeChunk(res)
    let time = 0
    for (let i = 0; i < 4; i++) {
      const timeout = this.#mock.types.number({ min: 1, max: 10 })
      time += timeout
      setTimeout(() => this.#writeChunk(res), timeout)
    }
    time += 5
    setTimeout(() => {
      res.end('END')
    }, time)
  }

  #writeChunk(res: Response): void {
    const word = this.#mock.lorem.word({ length: 128 })
    res.write(`${word}\n`)
  }
}

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