import bcrypt from 'bcrypt';
import { sendError } from '../utils/response.js';
import { GeneralService } from '../share/generalservice.js';
import redis from '../utils/redis.js';

export class ResetPasswordService {
  constructor() {
    // this.redis = new Redis();
    this.generalService = new GeneralService();
  }

  async resetPassword(email, token, newPassword) {
    let database = '';

    const storedToken = await redis.get(`reset:${email}`);
    if (!storedToken || storedToken !== token) {
      throw sendError('Token ไม่ถูกต้องหรือหมดอายุ', 'Invalid or expired token');
    }

    await redis.del(`reset:${email}`);

    // อัปเดตรหัสผ่านในฐานข้อมูลจริง
    const hashedPwd = await bcrypt.hash(newPassword, 10);
    let sql = `
    UPDATE usrmst SET usrpwd = $1 WHERE usrnam = $2
    `
    let param = [hashedPwd, email];
    await this.generalService.executeQueryParam(database, sql, param);

    this.generalService.devhint(1, 'resetpasswordservice.js', `Password reset successful (${email})`);

    return {
      code: '200',
      message: 'successful',
      message_th: 'รีเซ็ตรหัสผ่านสำเร็จ'
    };
  }
}
