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

export class RegisterService {

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

  async requestRegistration(database, email, fname, lname, password) {
    let result = [];
    try {
      let sql = `
        SELECT usrseq FROM ${database}.usrmst WHERE usrnam = $1
      `;
      let param = [email];
      const userCheck = await this.generalService.executeQueryParam(database, sql, param);

      if (userCheck.length > 0) {
        this.generalService.devhint(1, 'registerservice.js', `❌ Duplicate email (${email})`);
        throw sendError('อีเมลนี้ถูกใช้แล้ว', 'Email already registered');
      }

      const hashedPwd = await bcrypt.hash(password, 10);
      const token = crypto.randomBytes(32).toString('hex');


      const payload = JSON.stringify({ fname, lname, hashedPwd, token, database });
      await redis.set(`verify:${email}`, payload, 'EX', 86400); // 24h


      const verifyUrl = `http://localhost:1012/login/verify-email?token=${token}&email=${encodeURIComponent(email)}&organization=${database}`;
      await this.sendVerifyEmail(email, verifyUrl);

      this.generalService.devhint(2, 'registerservice.js', `✅ Verify link sent to ${email}`);

      result = {
        code: '200',
        message_th: 'ส่งลิงก์ยืนยันอีเมลแล้ว',
        data: {}
      };
    } catch (error) {
      this.generalService.devhint(1, 'registerservice.js', '❌ Registration Error', error.message);
      throw error;
    }
    return result;
  }

  async sendVerifyEmail(email, verifyUrl) {
    try {
      const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
          user: process.env.SMTP_USER,
          pass: process.env.SMTP_PASS,
        },
      });

      const html = `
        <div style="font-family: sans-serif;">
          <h2>ยืนยันการสมัครสมาชิก</h2>
          <p>กรุณากดยืนยันภายใน 24 ชั่วโมง เพื่อเปิดใช้งานบัญชีของคุณ</p>
          <a href="${verifyUrl}"
             style="display:inline-block;background:#0078d4;color:white;
             padding:10px 20px;text-decoration:none;border-radius:5px;">ยืนยันอีเมล</a>
          <p style="margin-top:16px;font-size:13px;color:#555;">หากคุณไม่ได้สมัคร โปรดละเว้นอีเมลนี้</p>
        </div>
      `;

      await transporter.sendMail({
        from: `"System" <${process.env.SMTP_USER}>`,
        to: email,
        subject: '📩 ยืนยันอีเมลสำหรับสมัครสมาชิก',
        html,
      });

      this.generalService.devhint(2, 'registerservice.js', `📤 Verification email sent (${email})`);
    } catch (error) {
      this.generalService.devhint(1, 'registerservice.js', '❌ Email Send Failed', error.message);
      throw sendError('ไม่สามารถส่งอีเมลได้', 'Email send failed');
    }
  }
}
