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

export function userController() {

  async function onNavigate(req, res) {
    const database = req.body.organization
    if (!database) {return sendResponse(res, 400, 'ไม่พบบริษัท', 'Missing organization')}
    const prommis = await onUserController(req, res, database)
    return prommis
  }

  async function onUserController(req, res, database) {
    try {
    var idx = -1
    let result = []
      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 }
}
