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

export class RegisterService {
  constructor() {
    this.generalService = new GeneralService()
  }

  async createUser(database, userData) {
    
    // 1. ทำการ Hash Password
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash(userData.password, saltRounds);

    // 2. เตรียม SQL
    const sql = `
      INSERT INTO ${database}.usrmst 
      (username, password, email, firstname, lastname, created_at)
      VALUES (?, ?, ?, ?, ?, NOW())
    `
    
    // 3. ใช้ hashedPassword แทน password เดิม
    const params = [
      userData.username,
      hashedPassword, // ส่งตัวที่ Hash แล้วเข้า DB
      userData.email,
      userData.firstname,
      userData.lastname
    ]

    try {
        const result = await this.generalService.executeQueryParam(database, sql, params);
        
        // เช็คผลลัพธ์ตาม Structure ของ GeneralService
        // สมมติว่าถ้า Error ตัว executeQueryParam อาจจะ throw หรือ return null
        return { status: true, message: 'Registration successful' }; 
    } catch (error) {
        console.error('Register Service Error:', error);
        return null; 
    }
  }

  async checkUserDuplicate(database, email) {
    const sql = `
      SELECT * FROM nuttakit.usrmst
      WHERE usreml = $1
    `
    const params = [email]
    const aryResult = await this.generalService.executeQueryParam(database, sql, params);
    return aryResult;
  }

  async genNum(database) {
    const sql = `
      SELECT 
        MAX(usrseq) as max_seq
      FROM nuttakit.usrmst
    `
    const params = []
    const aryResult = await this.generalService.executeQueryParam(database, sql, params);

    const lastSeq = aryResult[0]?.max_seq || 0;

    return lastSeq + 1;
  }
}