const express = require('express');
const bcrypt = require('bcrypt');
const crypto = require('crypto');

const { sendOrganizationVerificationEmail } =
  require('../utils/emailSender');

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

  router.post('/', async (req, res) => {
    const {
      organizationName,
      slug,
      country,
      mobile,
      adminFirstName,
      adminLastName,
      adminEmail,
      password
    } = req.body;

    if (
      !organizationName ||
      !slug ||
      !adminFirstName ||
      !adminLastName ||
      !adminEmail ||
      !password
    ) {
      return res.status(400).json({
        success: false,
        error: 'Missing required fields'
      });
    }

    const email = adminEmail.toLowerCase().trim();
    const passwordHash = await bcrypt.hash(password, 12);
    const verificationToken = crypto.randomBytes(32).toString('hex');
    const verificationExpires =
      new Date(Date.now() + 24 * 60 * 60 * 1000);

    const conn = await pool.getConnection();

    try {
      await conn.beginTransaction();

      // 1️⃣ Ensure org slug is unique
      const [[orgExists]] = await conn.query(
        'SELECT id FROM organizations WHERE slug = ?',
        [slug]
      );

      if (orgExists) {
        await conn.rollback();
        return res.json({
          success: false,
          error: 'Organization already exists'
        });
      }

      // 2️⃣ Create organization
      const [orgResult] = await conn.query(
        `
        INSERT INTO organizations
(name, slug, country, mobile, isVerified, verificationToken, verificationExpires)
VALUES (?, ?, ?, ?, 0, ?, ?)
        `,
        [
          organizationName,
          slug,
          country,
          mobile,
          verificationToken,
          verificationExpires
        ]
      );

      const organizationId = orgResult.insertId;

      // 3️⃣ Ensure admin email not reused in org
      const [[userExists]] = await conn.query(
        'SELECT id FROM users WHERE organizationId = ? AND email = ?',
        [organizationId, email]
      );

      if (userExists) {
        await conn.rollback();
        return res.json({
          success: false,
          error: 'Admin email already exists'
        });
      }

      // 4️⃣ Create admin user
      await conn.query(
        `
        INSERT INTO users
        (organizationId, email, firstName, lastName, password_hash, role)
        VALUES (?, ?, ?, ?, ?, 'owner')
        `,
        [
          organizationId,
          email,
          adminFirstName,
          adminLastName,
          passwordHash
        ]
      );

      await conn.commit();

      // 5️⃣ Send verification email
      await sendOrganizationVerificationEmail({
        to: email,
        organizationName,
        verificationToken
      });

      res.json({
        success: true,
        message:
          'Organization registered. Please verify your email.'
      });

    } catch (err) {
      await conn.rollback();
      console.error('Org registration error:', err);
      res.status(500).json({
        success: false,
        error: 'Server error'
      });
    } finally {
      conn.release();
    }
  });

  return router;
};
