const express = require('express');
console.log('ADMIN PROFILE ROUTE LOADED');

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

  /**
   * GET /dashboard/api/profile
   * Returns logged-in admin profile + organization
   */
  router.get('/profile', async (req, res) => {
    try {
      const userId = req.user.userId;

      const [[row]] = await pool.query(
        `
        SELECT
          u.firstName,
          u.lastName,
          u.email,
          u.role,
          o.name AS organizationName
        FROM users u
        JOIN organizations o ON o.id = u.organizationId
        WHERE u.id = ?
        `,
        [userId]
      );

      if (!row) {
        return res.status(404).json({
          success: false,
          error: 'User not found'
        });
      }

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

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

  return router;
};
