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

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

  async verifyOtp(email, otp) {
    const storedOtp = await redis.get(`otp:${email}`);
    if (!storedOtp || storedOtp !== otp) {
      throw sendError('รหัส OTP ไม่ถูกต้องหรือหมดอายุ', 'Invalid OTP');
    }

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

    const resetToken = crypto.randomBytes(32).toString('hex');
    await redis.set(`reset:${email}`, resetToken, 'EX', 600); // TTL 10 นาที

    this.generalService.devhint(1, 'otpverifyservice.js', `OTP Verified → Reset Token issued (${email})`);

    return {
        resetToken:resetToken
    };
  }
}
