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

const adminProfile = require('./admin/adminProfile');

module.exports = ({ pool }) => {

  const router = express.Router();

  /* -----------------------------------
     ADMIN PROFILE
     GET /admin/api/profile
  ------------------------------------ */
console.log('ADMIN ROUTES LOADED');

  router.use('/', adminProfile({ pool }));


  /* -----------------------------------
     INVITE USER
     POST /admin/api/invite-user
  ------------------------------------ */

  router.post('/invite-user', async (req, res) => {

    try {

      const { email, firstName, lastName } = req.body;
      const orgId = req.user.organizationId;

      if (!email || !firstName || !lastName) {
        return res.status(400).json({ error: 'Missing fields' });
      }

      const token = crypto.randomBytes(32).toString('hex');
      const expires = new Date(Date.now() + 48 * 60 * 60 * 1000);

      await pool.query(
        `
        INSERT INTO user_invites
        (organizationId, email, firstName, lastName, token, expires)
        VALUES (?, ?, ?, ?, ?, ?)
        `,
        [orgId, email.toLowerCase(), firstName, lastName, token, expires]
      );

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

      res.json({ success: true });

    } catch (err) {

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

    }
  });

  return router;
};
