import * as adminService from '../services/admin.service.js';
import * as statusService from '../services/status.service.js';
import { triggerEventNotifications } from '../cron/index.js';

/**
 * Vytvorenie nového usera s automatic temporary password (admin only)
 * Ak je poskytnutý email a emailPassword, automaticky sa fetchne JMAP account ID
 * POST /api/admin/users
 */
export const createUser = async (req, res, next) => {
  const { username, email, emailPassword, firstName, lastName, role } = req.body;
  const adminId = req.userId;
  const ipAddress = req.ip || req.connection.remoteAddress;
  const userAgent = req.headers['user-agent'];

  try {
    const result = await adminService.createUser(
      username,
      firstName,
      lastName,
      role,
      email,
      emailPassword,
      { userId: adminId, ipAddress, userAgent }
    );

    res.status(201).json({
      success: true,
      data: {
        user: {
          id: result.user.id,
          username: result.user.username,
          firstName: result.user.firstName,
          lastName: result.user.lastName,
          role: result.user.role,
          emailSetup: result.emailAccountCreated,
          emailAccount: result.emailAccountData,
          tempPassword: result.tempPassword,
        },
      },
      message: result.emailAccountCreated
        ? result.emailAccountData.shared
          ? 'Používateľ vytvorený a pripojený k existujúcemu zdieľanému email účtu.'
          : 'Používateľ úspešne vytvorený s novým emailovým účtom.'
        : 'Používateľ úspešne vytvorený. Email môže byť nastavený neskôr.',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Zoznam všetkých userov (admin only)
 * GET /api/admin/users
 */
export const getAllUsers = async (req, res, next) => {
  try {
    const allUsers = await adminService.getAllUsers();

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

/**
 * Získanie konkrétneho usera (admin only)
 * GET /api/admin/users/:userId
 */
export const getUser = async (req, res, next) => {
  const { userId } = req.params;

  try {
    const user = await adminService.getUserById(userId);

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

/**
 * Zmena role usera (admin only)
 * PATCH /api/admin/users/:userId/role
 */
export const changeUserRole = async (req, res, next) => {
  const { userId } = req.params;
  const { role } = req.body;
  const adminId = req.userId;
  const ipAddress = req.ip || req.connection.remoteAddress;
  const userAgent = req.headers['user-agent'];

  try {
    const result = await adminService.changeUserRole(userId, role, { userId: adminId, ipAddress, userAgent });

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

/**
 * Update user details (admin only)
 * PATCH /api/admin/users/:userId
 */
export const updateUser = async (req, res, next) => {
  const { userId } = req.params;
  const { firstName, lastName } = req.body;

  try {
    const updated = await adminService.updateUser(userId, { firstName, lastName });

    res.status(200).json({
      success: true,
      data: updated,
      message: 'Používateľ bol aktualizovaný',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Reset user password (admin only)
 * POST /api/admin/users/:userId/reset-password
 */
export const resetUserPassword = async (req, res, next) => {
  const { userId } = req.params;

  try {
    const result = await adminService.resetUserPassword(userId);

    res.status(200).json({
      success: true,
      data: { tempPassword: result.tempPassword },
      message: 'Heslo bolo resetované',
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Zmazanie usera (admin only)
 * DELETE /api/admin/users/:userId
 */
export const deleteUser = async (req, res, next) => {
  const { userId } = req.params;
  const adminId = req.userId;
  const ipAddress = req.ip || req.connection.remoteAddress;
  const userAgent = req.headers['user-agent'];

  try {
    const result = await adminService.deleteUser(userId, { userId: adminId, ipAddress, userAgent });

    res.status(200).json({
      success: true,
      message: 'Používateľ bol zmazaný',
      deletedEmailAccounts: result.deletedEmailAccounts,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * Get server status (admin only)
 * GET /api/admin/server-status
 */
export const getServerStatus = async (req, res, next) => {
  try {
    const status = await statusService.getServerStatus();

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

/**
 * Manually trigger event notifications (admin only, for testing)
 * POST /api/admin/trigger-notifications
 */
export const triggerNotifications = async (req, res, next) => {
  try {
    const stats = await triggerEventNotifications();

    res.status(200).json({
      success: true,
      data: stats,
      message: `Notifikácie odoslané: ${stats.sent}, neúspešné: ${stats.failed}, preskočené: ${stats.skipped}`,
    });
  } catch (error) {
    next(error);
  }
};
