const express = require('express');

module.exports = ({ pool }) => {
  const router = express.Router();

  /**
   * GET /organization/verify-email?token=...
   * Verifies organization email
   */
  router.get('/', async (req, res) => {
    const { token } = req.query;

    if (!token) {
      return res.status(400).json({
        success: false,
        error: 'Invalid verification link'
      });
    }

    try {
      const [[org]] = await pool.query(
        `
        SELECT id, isVerified, verificationExpires
        FROM organizations
        WHERE verificationToken = ?
        `,
        [token]
      );

      if (!org) {
        return res.status(400).json({
          success: false,
          error: 'Invalid or expired verification link'
        });
      }

      if (org.isVerified) {
        return res.json({
          success: true,
          message: 'Organization already verified'
        });
      }

      if (org.verificationExpires < new Date()) {
        return res.status(400).json({
          success: false,
          error: 'Verification link has expired'
        });
      }

      await pool.query(
        `
        UPDATE organizations
        SET isVerified = 1,
            verificationToken = NULL,
            verificationExpires = NULL
        WHERE id = ?
        `,
        [org.id]
      );

      return res.json({
        success: true,
        message: 'Email verified successfully'
      });

    } catch (err) {
      console.error('Verification error:', err);
      return res.status(500).json({
        success: false,
        error: 'Server error'
      });
    }
  });

  return router;
};
