const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
const pool = require('../db');
const fs = require('fs');
const path = require('path');
const nodemailer = require('nodemailer');
const emailNormalized = email.toLowerCase().trim();


/* -----------------------------
   EMAIL SETUP
------------------------------ */
const transporter = nodemailer.createTransport({
    host: 'smtp.yourprovider.com',
    port: 587,
    secure: false,
    auth: {
        user: 'info@gocrm.net',
        pass: process.env.EMAIL_PASSWORD
    }
});

/* -----------------------------
   HELPERS
------------------------------ */
function createOrgFolders(orgId) {
    const base = `/var/www/saas.gocrm.net/orgs/org_${orgId}`;
    const folders = ['uploads', 'project_files', 'chat_files'];

    folders.forEach(folder => {
        const dir = path.join(base, folder);
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
    });
}

/* ============================================================
   POST /organization/register
============================================================ */
router.post('/register', async (req, res) => {
    const {
        organizationName,
        slug,
        firstName,
        lastName,
        email,
        password,
        country,
        mobile
    } = req.body;

    try {
        const passwordHash = await bcrypt.hash(password, 12);
        const verificationToken = crypto.randomBytes(32).toString('hex');

        //verify that email doesnt already exist
        const [[exists]] = await pool.query(
            'SELECT id FROM organizations WHERE slug = ? OR adminEmail = ?',
            [slug, emailNormalized]
        );

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


        await pool.query(`
      INSERT INTO organizations
      (name, slug, adminFirstName, adminLastName, adminEmail,
       adminPasswordHash, country, mobile, isVerified, verificationToken, verificationExpires)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)
    `, [
            organizationName,
            slug,
            firstName,
            lastName,
            emailNormalized,
            passwordHash,
            country,
            mobile,
            verificationToken,
            NOW()
        ]);

        const verifyLink = `${process.env.BASE_URL}/organization/verify?token=${verificationToken}`;

        await transporter.sendMail({
            from: `"GoCRM" <info@gocrm.net>`,
            to: email,
            subject: 'Verify your organization',
            html: `
        <h3>Welcome to GoCRM</h3>
        <p>Please verify your organization:</p>
        <a href="${verifyLink}">${verifyLink}</a>
      `
        });

        res.json({ success: true, message: 'Verification email sent' });

    } catch (err) {
        console.error('Org register error:', err);
        res.status(500).json({ success: false });
    }
});

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

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

        if (!org) {
            return res.status(400).send('Invalid or expired token');
        }

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

        createOrgFolders(org.id);

        res.send('Organization verified successfully');

    } catch (err) {
        console.error('Verification error:', err);
        res.status(500).send('Verification failed');
    }
});

/* ============================================================
   POST /organization/login   (ADMIN LOGIN)
============================================================ */
router.post('/login', async (req, res) => {
    const { email, password } = req.body;

    try {
        const [[org]] = await pool.query(`
      SELECT id, name, adminPasswordHash, isVerified
      FROM organizations WHERE adminEmail = ?
    `, [email]);

        if (!org || !org.isVerified) {
            return res.json({ success: false, error: 'Invalid credentials' });
        }

        const match = await bcrypt.compare(password, org.adminPasswordHash);
        if (!match) {
            return res.json({ success: false, error: 'Invalid credentials' });
        }
        console.log('SIGN JWT_SECRET:', process.env.JWT_SECRET);

        // org is fetched from DB
        // org.adminUserId MUST exist

        console.log('SIGN JWT_SECRET:', process.env.JWT_SECRET);

        const token = jwt.sign(
            {
                userId: org.adminUserId,     // ✅ REQUIRED
                organizationId: org.id,      // ✅ REQUIRED
                role: 'owner'                // or 'admin'
            },
            process.env.JWT_SECRET,
            { expiresIn: '12h' }
        );


        res.json({
            success: true,
            token,
            organizationId: org.id,
            organizationName: org.name
        });

    } catch (err) {
        console.error('Org login error:', err);
        res.status(500).json({ success: false });
    }
});



/* ============================================================
   DELETE /organization/users/:userId
   Remove user from organization
============================================================ */
router.delete(
    '/users/:userId',
    verifyOrgAdminToken,
    async (req, res) => {
        const { userId } = req.params;
        const organizationId = req.organizationId;

        try {
            await pool.query(`
        DELETE FROM organization_users
        WHERE organizationId = ? AND userId = ?
      `, [organizationId, userId]);

            res.json({
                success: true,
                message: 'User removed from organization'
            });

        } catch (err) {
            console.error('Remove user error:', err);
            res.status(500).json({ success: false });
        }
    }
);

router.get('/admin/me', verifyOrgAdminToken, async (req, res) => {

  try {

    const adminId = req.user.id;

    const [rows] = await pool.query(
      `
      SELECT
        id,
        email,
        firstName,
        lastName,
        role,
        organizationId
      FROM users
      WHERE id = ?
      `,
      [adminId]
    );

    res.json({
      success: true,
      user: rows[0]
    });

  } catch (err) {

    console.error('ADMIN ME ERROR:', err);
    res.status(500).json({ success: false });

  }
});


module.exports = router;
