import * as companyService from '../services/company.service.js';

export const getCompanyUsers = async (req, res, next) => {
  try {
    const { companyId } = req.params;

    const users = await companyService.getCompanyUsers(companyId);

    res.status(200).json({
      success: true,
      count: users.length,
      data: users,
    });
  } catch (error) {
    next(error);
  }
};

export const assignUserToCompany = async (req, res, next) => {
  try {
    const currentUserId = req.userId;
    const { companyId } = req.params;
    const { userId, role } = req.body;

    const assignment = await companyService.assignUserToCompany(companyId, userId, currentUserId, role, { userId: currentUserId, ipAddress: req.ip, userAgent: req.headers['user-agent'] });

    res.status(201).json({
      success: true,
      data: assignment,
      message: 'Používateľ bol priradený k firme',
    });
  } catch (error) {
    next(error);
  }
};

export const removeUserFromCompany = async (req, res, next) => {
  try {
    const currentUserId = req.userId;
    const { companyId, userId } = req.params;

    const result = await companyService.removeUserFromCompany(companyId, userId, { userId: currentUserId, ipAddress: req.ip, userAgent: req.headers['user-agent'] });

    res.status(200).json({
      success: true,
      message: result.message,
    });
  } catch (error) {
    next(error);
  }
};

export const updateUserRoleOnCompany = async (req, res, next) => {
  try {
    const { companyId, userId } = req.params;
    const { role } = req.body;

    const assignment = await companyService.updateUserRoleOnCompany(companyId, userId, role);

    res.status(200).json({
      success: true,
      data: assignment,
      message: 'Rola používateľa bola aktualizovaná',
    });
  } catch (error) {
    next(error);
  }
};
