import { UserMaster } from '../models/index.js';
import { successResponse, errorResponse } from '../utils/response.js';

// Get all roles
async function getAllRoles(req, res) {
  try {
    const roles = await UserMaster.findAll({
      order: [['sort_order', 'ASC']]
    });
    
    return successResponse(res, 200, 'Roles fetched successfully', roles);
  } catch (error) {
    console.error('Error fetching roles:', error);
    return errorResponse(res, 500, 'Error fetching roles', error.message);
  }
}

// Get active roles only
async function getActiveRoles(req, res) {
  try {
    const roles = await UserMaster.findAll({
      where: { is_active: true },
      order: [['sort_order', 'ASC']]
    });
    
    return successResponse(res, 200, 'Active roles fetched successfully', roles);
  } catch (error) {
    console.error('Error fetching active roles:', error);
    return errorResponse(res, 500, 'Error fetching active roles', error.message);
  }
}

// Get role by ID
async function getRoleById(req, res) {
  try {
    const { id } = req.params;
    const role = await UserMaster.findByPk(id);
    
    if (!role) {
      return errorResponse(res, 404, 'Role not found');
    }
    
    return successResponse(res, 200, 'Role fetched successfully', role);
  } catch (error) {
    console.error('Error fetching role:', error);
    return errorResponse(res, 500, 'Error fetching role', error.message);
  }
}

// Create new role
async function createRole(req, res) {
  try {
    const {
      role_name,
      role_display_name,
      description,
      permissions = {},
      is_active = true,
      sort_order = 0
    } = req.body;

    // Validate required fields
    if (!role_name || !role_display_name) {
      return errorResponse(res, 400, 'role_name and role_display_name are required');
    }

    // Check if role_name already exists
    const existingRole = await UserMaster.findOne({ where: { role_name } });
    if (existingRole) {
      return errorResponse(res, 400, 'Role name already exists');
    }

    const role = await UserMaster.create({
      role_name,
      role_display_name,
      description,
      permissions,
      is_active,
      sort_order,
      created_by: req.user?.login_id
    });

    return successResponse(res, 201, 'Role created successfully', role);
  } catch (error) {
    console.error('Error creating role:', error);
    return errorResponse(res, 500, 'Error creating role', error.message);
  }
}

// Update role
async function updateRole(req, res) {
  try {
    const { id } = req.params;
    const {
      role_name,
      role_display_name,
      description,
      permissions,
      is_active,
      sort_order
    } = req.body;

    const role = await UserMaster.findByPk(id);
    if (!role) {
      return errorResponse(res, 404, 'Role not found');
    }

    // Check if role_name already exists (excluding current role)
    if (role_name && role_name !== role.role_name) {
      const existingRole = await UserMaster.findOne({ 
        where: { role_name, id: { [require('sequelize').Op.ne]: id } }
      });
      if (existingRole) {
        return errorResponse(res, 400, 'Role name already exists');
      }
    }

    await role.update({
      role_name: role_name || role.role_name,
      role_display_name: role_display_name || role.role_display_name,
      description: description !== undefined ? description : role.description,
      permissions: permissions !== undefined ? permissions : role.permissions,
      is_active: is_active !== undefined ? is_active : role.is_active,
      sort_order: sort_order !== undefined ? sort_order : role.sort_order
    });

    return successResponse(res, 200, 'Role updated successfully', role);
  } catch (error) {
    console.error('Error updating role:', error);
    return errorResponse(res, 500, 'Error updating role', error.message);
  }
}

// Delete role (soft delete by setting is_active to false)
async function deleteRole(req, res) {
  try {
    const { id } = req.params;
    const role = await UserMaster.findByPk(id);
    
    if (!role) {
      return errorResponse(res, 404, 'Role not found');
    }

    // Check if role is being used by any users
    const { Login } = require('../models/index.js');
    const usersWithRole = await Login.count({ where: { role_id: id } });
    
    if (usersWithRole > 0) {
      return errorResponse(res, 400, 'Cannot delete role that is assigned to users');
    }

    // Soft delete by setting is_active to false
    await role.update({ is_active: false });

    return successResponse(res, 200, 'Role deactivated successfully');
  } catch (error) {
    console.error('Error deleting role:', error);
    return errorResponse(res, 500, 'Error deleting role', error.message);
  }
}

// Get role permissions
async function getRolePermissions(req, res) {
  try {
    const { id } = req.params;
    const role = await UserMaster.findByPk(id);
    
    if (!role) {
      return errorResponse(res, 404, 'Role not found');
    }

    return successResponse(res, 200, 'Role permissions fetched successfully', {
      role_id: role.id,
      role_name: role.role_name,
      permissions: role.permissions
    });
  } catch (error) {
    console.error('Error fetching role permissions:', error);
    return errorResponse(res, 500, 'Error fetching role permissions', error.message);
  }
}

export {
  getAllRoles,
  getActiveRoles,
  getRoleById,
  createRole,
  updateRole,
  deleteRole,
  getRolePermissions
};
