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

const express = require('express');
const crypto = require('crypto');
const pool = require('../db');
const requireOrgPermission = require('../middleware/requireOrgPermission');

const router = express.Router();

/* ============================================================
   POST /dashboard/invites/create
   Create invite (ORG ADMIN)
============================================================ */
router.post(
  '/create',
  requireOrgPermission('USER_MANAGEMENT'),
  async (req, res) => {
    const { email, role = 'user' } = req.body;
    const organizationId = req.organizationId;
    const invitedBy = req.user.id;

    if (!email) {
      return res.status(400).json({ error: 'Email required' });
    }

    try {
      const token = crypto.randomBytes(32).toString('hex');
      const expiresAt = new Date(Date.now() + 72 * 60 * 60 * 1000); // 72h

      await pool.query(`
        INSERT INTO user_invites
          (organizationId, email, role, token, invitedBy, expiresAt)
        VALUES (?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE
          token = VALUES(token),
          role = VALUES(role),
          invitedBy = VALUES(invitedBy),
          expiresAt = VALUES(expiresAt),
          status = 'pending'
      `, [
        organizationId,
        email.toLowerCase().trim(),
        role,
        token,
        invitedBy,
        expiresAt
      ]);

      const inviteLink =
        `${process.env.BASE_URL}/invite/accept?token=${token}`;

      await sendUserInviteEmail({
        to: email,
        token
      });


      res.json({
        success: true,
        inviteLink
      });

    } catch (err) {
      console.error('Create invite error:', err);
      res.status(500).json({ error: 'Failed to create invite' });
    }
  }
);

/* ============================================================
   GET /dashboard/invites/list
============================================================ */
router.get(
  '/list',
  requireOrgPermission('USER_MANAGEMENT'),
  async (req, res) => {
    const organizationId = req.organizationId;

    try {
      const [invites] = await pool.query(`
        SELECT
          inviteID,
          email,
          role,
          status,
          expiresAt,
          createdAt,
          acceptedAt
        FROM user_invites
        WHERE organizationId = ?
        ORDER BY createdAt DESC
      `, [organizationId]);

      res.json({ success: true, invites });

    } catch (err) {
      console.error('List invites error:', err);
      res.status(500).json({ error: 'Failed to fetch invites' });
    }
  }
);

/* ============================================================
   POST /dashboard/invites/revoke
============================================================ */
router.post(
  '/revoke',
  requireOrgPermission('USER_MANAGEMENT'),
  async (req, res) => {
    const { inviteID } = req.body;
    const organizationId = req.organizationId;

    if (!inviteID) {
      return res.status(400).json({ error: 'inviteID required' });
    }

    try {
      await pool.query(`
        UPDATE user_invites
        SET status = 'revoked'
        WHERE inviteID = ?
          AND organizationId = ?
          AND status = 'pending'
      `, [inviteID, organizationId]);

      res.json({ success: true });

    } catch (err) {
      console.error('Revoke invite error:', err);
      res.status(500).json({ error: 'Failed to revoke invite' });
    }
  }
);

module.exports = router;
