const express = require('express')
const router = express.Router()
const { authenticateToken, authorizePermission } = require('../middleware/auth')
const { pool } = require('../config/database')
const RoleController = require('../controllers/roleController')

// All routes require authentication
router.use(authenticateToken)

// GET /api/roles - Get all roles with permissions
// Allow org admins/users with role.read to load roles list in Settings, while keeping manage_permissions for full admin tooling.
router.get('/', authorizePermission('role.manage_permissions', 'role.read'), RoleController.getRolesWithPermissions)

// GET /api/roles/organization-dialog - Get roles for organization dialog (organization_id in (1,0) and id != 1)
router.get('/organization-dialog', authorizePermission('role.read'), RoleController.getRolesForOrganizationDialog)

// GET /api/roles/permissions - Get all permissions (MUST be before /:id route)
// Allow either explicit permission.read or broader role.manage_permissions so role admins can load dynamic Actions list.
router.get('/permissions', authorizePermission('permission.read', 'role.manage_permissions'), RoleController.getPermissions)

// POST /api/roles/permissions - Create new permission
router.post('/permissions', authorizePermission('permission.create'), RoleController.createPermission)

// PUT /api/roles/permissions/:id - Update permission
router.put('/permissions/:id', authorizePermission('permission.update'), RoleController.updatePermission)

// DELETE /api/roles/permissions/:id - Delete permission
router.delete('/permissions/:id', authorizePermission('permission.delete'), RoleController.deletePermission)

// GET /api/roles/:id - Get specific role
router.get('/:id', authorizePermission('role.read'), async (req, res) => {
  try {
    const { id } = req.params
    const organization_id = req.user?.organization_id

    let query = `SELECT id, name, organization_id, description, level, is_active, created_at, updated_at 
       FROM roles 
       WHERE id = ? AND is_active = 1`

    const params = [id]

    if (organization_id) {
      query += ' AND organization_id = ?'
      params.push(organization_id)
    }

    const [roles] = await pool.execute(query, params)

    if (roles.length === 0) {
      return res.status(404).json({
        status: 'error',
        message: 'Role not found'
      })
    }

    res.status(200).json({
      status: 'success',
      data: roles[0]
    })
  } catch (error) {
    console.error('Error fetching role:', error)
    res.status(500).json({
      status: 'error',
      message: 'Failed to fetch role'
    })
  }
})

// POST /api/roles - Create new role (with permissions support)
router.post('/', authorizePermission('role.create'), RoleController.createRole)

// PUT /api/roles/:id - Update role (with permissions support)
router.put('/:id', authorizePermission('role.update'), RoleController.updateRole)

// DELETE /api/roles/:id - Delete role
router.delete('/:id', authorizePermission('role.delete'), RoleController.deleteRole)

module.exports = router
