import bcrypt from 'bcrypt'
import { GeneralService } from '../share/generalservice.js'
import { generateToken } from '../utils/token.js'

export class LoginService {
  constructor() {
    this.generalService = new GeneralService()
  }
  async verifyLogin(database, username, password) {
    this.generalService.devhint(2, 'loginservice.js', `verifyLogin() start for username=${username}`)

    let user = null
    let token = null

    let sql = `
      SELECT usrseq, usrnam, usrorg, usrrol, usrpwd, usrthinam, usrthilstnam
      FROM nuttakit.usrmst
      WHERE usrnam = $1
    `
    let params = [username]
    const rows = await this.generalService.executeQueryParam(database, sql, params)
    this.generalService.devhint(3, 'loginservice.js', `query done, found=${rows.length}`)

    if (rows.length === 0) {
      this.generalService.devhint(2, 'loginservice.js', 'no user found')
      return null
    }

    user = rows[0]
    const match = await bcrypt.compare(password, user.usrpwd)
    if (match === false) {
      this.generalService.devhint(2, 'loginservice.js', 'password mismatch')
      return null
    }

    token = generateToken({
      id: user.usrseq,
      name: user.usrnam,
      realname: user.usrthinam,
      lastname: user.usrthilstnam,
      role: user.usrrol,
      organization: user.usrorg
    })
    this.generalService.devhint(2, 'loginservice.js', 'token generated successfully')


    delete user.usrseq  
    delete user.usrnam  
    delete user.usrrol  
    delete user.usrpwd
    delete user.usrorg
    return {
      token,
      ...user
    }
  }

  async loginWithBiometric(database, biometric_id) {
    this.generalService.devhint(2, 'loginservice.js', `loginWithBiometric() start for biometric_id=${biometric_id}`)

    let sql = ''
    let params = []

    sql = `
      SELECT usrid, usrnam, usrrol
      FROM ${database}.usrmst
      WHERE biometric_id = $1
    `
    params = [biometric_id]
    const rows = await this.generalService.executeQueryParam(database, sql, params)
    if (rows.length === 0) {
      this.generalService.devhint(2, 'loginservice.js', 'no biometric found')
      return null
    }

    const user = rows[0]
    const token = generateToken({
      id: user.usrid,
      name: user.usrnam,
      role: user.usrrol,
      organization: database
    })

    this.generalService.devhint(2, 'loginservice.js', 'biometric token generated')
    return { token, user }
  }

  async registerBiometric(database, usrid, biometric_id) {
    this.generalService.devhint(2, 'loginservice.js', `registerBiometric() start user=${usrid}`)


    let sql = ''
    let params = []

    sql = `
      UPDATE ${database}.usrmst
      SET biometric_id = $1
      WHERE usrid = $2
    `
    params = [biometric_id, usrid]
    await this.generalService.executeQueryParam(database, sql, params)

    this.generalService.devhint(2, 'loginservice.js', 'biometric registered')
    return { message: 'Biometric registered successfully' }
  }
}
