// src/repositories/push.repo.js
const db = require('../db/knex');

async function findByUserAndEndpoint(user_id, endpoint) {
    return db('push_subscriptions').where({ user_id, endpoint }).first();
}

async function findByEndpoint(endpoint) {
    return db('push_subscriptions').where({ endpoint }).first();
}

async function listByUser(user_id) {
    return db('push_subscriptions')
        .where({ user_id })
        .select('id', 'endpoint', 'p256dh', 'auth');
}

async function insertSubscription(data) {
    const [row] = await db('push_subscriptions').insert(data).returning('*');
    return row;
}

async function deleteByUserAndEndpoint(user_id, endpoint) {
    return db('push_subscriptions').where({ user_id, endpoint }).del();
}

async function deleteById(id) {
    return db('push_subscriptions').where({ id }).del();
}

module.exports = {
    findByUserAndEndpoint,
    findByEndpoint,
    listByUser,
    insertSubscription,
    deleteByUserAndEndpoint,
    deleteById,
};
