// Registered push endpoints (Android/UnifiedPush v1). A device belongs to one
// user; the endpoint is the distributor URL the app's ntfy topic was handed. The
// endpoint is validated (HTTPS + allowed origin) by utils/pushDispatch before it
// is ever stored or published to — see that module's isAllowedEndpoint.

const db = require('./pushDevices.db')

function toSafe(row) {
  if (!row) return null
  return {
    id: row.id,
    transport: row.transport,
    endpoint: row.endpoint,
    platform: row.platform || null,
    createdAt: row.created_at,
    lastSeenAt: row.last_seen_at,
  }
}

const register = async ({ userId, transport, endpoint, platform }) =>
  toSafe(await db.upsert({ userId, transport, endpoint, platform }))

const listForUser = async (userId) => (await db.listByUser(userId)).map(toSafe)

// Returns true if a row was deleted (the device existed and belonged to userId).
const remove = async (id, userId) => (await db.remove(id, userId)) > 0

// Fan-out helpers: raw { endpoint, transport } rows (not toSafe-shaped).
const endpointsForStream = (streamId) => db.endpointsForStream(streamId)
const endpointsForUserStream = (userId, streamId) => db.endpointsForUserStream(userId, streamId)

module.exports = { register, listForUser, remove, endpointsForStream, endpointsForUserStream }
