import { LoginService } from '../services/loginservice.js'
import { sendError } from '../utils/response.js'
// import { OftenError } from '../utils/oftenError.js'
import { GeneralService } from '../share/generalservice.js';
import { trim_all_array } from '../utils/trim.js'
import { verifyToken, generateToken } from '../utils/token.js'

export class loginController {

  constructor() {
    this.generalService = new GeneralService();
    this.loginService = new LoginService();
  }

  async onNavigate(req, res) {
    this.generalService.devhint(1, 'logincontroller.js', 'onNavigate() start');
    let organization = req.body.organization;
    const prommis = await this.onLoginController(req, res, organization);
    return prommis;
  }

  async onLoginController(req, res, database) {
    let idx = -1
    let result = []
    try {
      let username = req.body.request.username;
      let password = req.body.request.password;

      result = await this.loginService.verifyLogin(database, username, password); // เช็คกับ db กลาง ส่ง jwttoken ออกมา
      this.generalService.devhint(1, 'logincontroller.js', 'Login success');
    } catch (error) {
      idx = 1;
    } finally { 
      if (idx === 1) return sendError('เกิดข้อผิดพลาดไม่คาดคิดเกิดขึ้น', 'Unexpected error');
      if (!result) return sendError('ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง', 'Invalid credentials');
      if(result) { return result }
      return null
    }
  }

  // async onBiometricLogin(req, res) {
  //   try {

  //   const result = await this.loginService.loginWithBiometric(organization, biometric_id)
  // } catch (error) {
  //   idx = 1
  // } finally { // สำคัญมากต้อง จดจำไม่มีดัดแปลง อัปเดทเลย เรื่อง idx 
  //   if(idx == 1){ return sendResponse(res, 400, 'เกิดข้อผิดพลาดไม่คาดคิดเกิดขึ้น', 'Unexpected error') }
  // }
  //   return { result, timestamp: new Date().toISOString() }
  // }

  // async onBiometricRegister(req, res) {
  //   const { organization, request } = req.body || {}
  //   const { biometric_id } = request || {}
  //   const userId = req.user.id

  //   const result = await this.loginService.registerBiometric(organization, userId, biometric_id)
  //   return { result, timestamp: new Date().toISOString() }
  // }

  // async onRenewToken(req, res) {
  //   const user = req.user
  //   const newToken = generateToken({ id: user.id, name: user.name })
  //   return { token: newToken, renewed_at: new Date().toISOString() }
  // }
}
