import { VerifyEmailService } from '../services/verifyemailservice.js';
import { sendError } from '../utils/response.js';
import { GeneralService } from '../share/generalservice.js';

export class VerifyEmailController {
  constructor() {
    this.verifyService = new VerifyEmailService();
    this.generalService = new GeneralService();
  }

  async onVerifyEmail(req, res) {
    let idx = -1;
    let result = null;

    try {
      // token/email can come from query (link) or body
      const email = (req.query && req.query.email) || (req.body && req.body.request && req.body.request.email);
      const token = (req.query && req.query.token) || (req.body && req.body.request && req.body.request.token);
      const schema = (req.query && req.query.organization) || (req.body && req.body.organization) || 'nuttakit';

      if (!email || !token) {
        return sendError('Missing token or email', 'Missing token or email', 400);
      }

      // call service to do Redis + DB work
      result = await this.verifyService.verifyAndCreate({ email, token, schema });

      // devhint success
      this.generalService.devhint(1, 'verifyemailcontroller.js', `Verify succeeded for ${email} schema=${schema}`);
    } catch (error) {
      idx = 1;
      // If service threw sendError object, it may be an object not Error
      const errMsg = (error && error.message) ? error.message : JSON.stringify(error);
      this.generalService.devhint(1, 'verifyemailcontroller.js', 'Jumpout Detected', errMsg);
    } finally {
      if (idx === 1) return sendError('ไม่สามารถยืนยันอีเมลได้', 'Verification failed', 400);
      // standard success response (globalResponseHandler will wrap it)
      return {
        code: '200',
        message: 'successful',
        message_th: 'ยืนยันอีเมลสำเร็จ',
        data: result
      };
    }
  }
}
