import { userService } from '../services/userservice.js'
import { trim_all_array } from '../utils/trim.js'
import { sendResponse } from '../utils/response.js'

export function userController() {

  async function onNavigate(req, res) {
    const database = req.body.organization
    if (!database) throw new Error('Missing organization')

    const prommis = await onUserController(req, res, database)
    return prommis
  }

  async function onUserController(req, res, database) {
    let idx = -1
    let result
    const { usrnam, usreml } = req.body

    try {
      result = await userService.createUser(database, usrnam, usreml)
    } 
    catch (err) {
      idx = 1
    } 
    finally {
      if (idx === 1) {
        return sendResponse(res, 400, 'เกิดข้อผิดพลาดไม่คาดคิดเกิดขึ้น', 'Unexpected error')
      }

      trim_all_array(result)
      const array_diy = {
        result,
        count: result.length,
        timestamp: new Date().toISOString(),
      }

      return array_diy
    }
  }

  return { onNavigate }
}
