// src/services/pushHttp.service.js
const pushRepo = require('../repositories/push.repo');
const { httpError } = require('../utils/httpError');

async function subscribe(userId, endpoint, keys, userAgent) {
  if (!endpoint || !keys?.p256dh || !keys?.auth) {
    throw httpError(400, 'Subscription inválida');
  }

  // dedupe (mesmo user)
  const existing = await pushRepo.findByUserAndEndpoint(userId, endpoint);
  if (existing) return { row: existing, created: false };

  // como endpoint é UNIQUE na tabela, evita conflito com outro user
  const usedByOther = await pushRepo.findByEndpoint(endpoint);
  if (usedByOther && usedByOther.user_id !== userId) {
    throw httpError(409, 'Este endpoint já está associado a outro utilizador');
  }

  const inserted = await pushRepo.insertSubscription({
    user_id: userId,
    endpoint,
    p256dh: keys.p256dh,
    auth: keys.auth,
    user_agent: userAgent || null,
    created_at: new Date().toISOString(),
  });

  return { row: inserted, created: true };
}

async function unsubscribe(userId, endpoint) {
  if (!endpoint) return { ok: true, message: 'No subscription' };
  await pushRepo.deleteByUserAndEndpoint(userId, endpoint);
  return { ok: true, message: 'Unsubscribed' };
}

module.exports = { subscribe, unsubscribe };
