const { PushToken } = require('../models');

exports.register = async (req, res) => {
  try {
    const { email, token, platform } = req.body;
    if (!email || !token) {
      return res.status(400).json({ error: 'Email and token are required' });
    }

    const [record] = await PushToken.upsert({
      email,
      token,
      platform: platform || 'android',
    });

    res.json({ message: 'Push token registered', token: record });
  } catch (error) {
    console.error('[PushToken] Register error:', error.message);
    res.status(500).json({ error: 'Failed to register push token' });
  }
};

exports.unregister = async (req, res) => {
  try {
    const { token } = req.body;
    if (!token) {
      return res.status(400).json({ error: 'Token is required' });
    }

    await PushToken.destroy({ where: { token } });
    res.json({ message: 'Push token unregistered' });
  } catch (error) {
    console.error('[PushToken] Unregister error:', error.message);
    res.status(500).json({ error: 'Failed to unregister push token' });
  }
};
