import * as pushService from '../services/push.service.js';
import { logger } from '../utils/logger.js';

/**
 * Get VAPID public key
 */
export const getVapidPublicKey = (req, res) => {
  const publicKey = pushService.getVapidPublicKey();

  if (!publicKey) {
    return res.status(503).json({
      success: false,
      message: 'Push notifikácie nie sú nakonfigurované',
    });
  }

  res.json({
    success: true,
    data: { publicKey },
  });
};

/**
 * Subscribe to push notifications
 */
export const subscribe = async (req, res, next) => {
  try {
    const { subscription } = req.body;
    const userId = req.user.id;

    if (!subscription || !subscription.endpoint || !subscription.keys) {
      return res.status(400).json({
        success: false,
        message: 'Neplatná subscription',
      });
    }

    await pushService.saveSubscription(userId, subscription);

    res.json({
      success: true,
      message: 'Push notifikácie aktivované',
    });
  } catch (error) {
    logger.error('Subscribe error', error);
    next(error);
  }
};

/**
 * Unsubscribe from push notifications
 */
export const unsubscribe = async (req, res, next) => {
  try {
    const { endpoint } = req.body;
    const userId = req.user.id;

    if (endpoint) {
      await pushService.removeSubscription(userId, endpoint);
    } else {
      await pushService.removeAllSubscriptions(userId);
    }

    res.json({
      success: true,
      message: 'Push notifikácie deaktivované',
    });
  } catch (error) {
    logger.error('Unsubscribe error', error);
    next(error);
  }
};

/**
 * Check subscription status
 */
export const getStatus = async (req, res, next) => {
  try {
    const userId = req.user.id;
    const hasSubscription = await pushService.hasActiveSubscription(userId);

    res.json({
      success: true,
      data: {
        enabled: hasSubscription,
        supported: !!pushService.getVapidPublicKey(),
      },
    });
  } catch (error) {
    logger.error('Get status error', error);
    next(error);
  }
};

/**
 * Test push notification (for debugging)
 */
export const testPush = async (req, res, next) => {
  try {
    const userId = req.user.id;

    const result = await pushService.sendPushNotification(userId, {
      title: 'Test notifikácie',
      body: 'Toto je testovacia push notifikácia z CRM',
      icon: '/icon-192.png',
      data: { url: '/' },
    });

    res.json({
      success: true,
      data: result,
    });
  } catch (error) {
    logger.error('Test push error', error);
    next(error);
  }
};
