// Account-linking store: maps external SSO identities to internal users. Thin
// logic layer over userIdentities.db (mirrors the users model split).

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

// The link-only login lookup. Returns the identity row (with user_id) or null.
async function findByProviderSubject(provider, subject) {
  return db.findByProviderSubject(provider, subject)
}

// Identities linked to a user (Account page).
async function listForUser(userId) {
  return db.listForUser(userId)
}

// Link an external identity to an internal user. Returns the new row id. The
// (provider, subject) UNIQUE constraint enforces one-identity-one-user at the DB.
async function link({ userId, provider, subject, email }) {
  return db.insert({ userId, provider, subject, email })
}

// Unlink a provider from a user. Returns rows removed (0 if nothing was linked).
async function unlink(userId, provider) {
  return db.deleteForUserProvider(userId, provider)
}

module.exports = { findByProviderSubject, listForUser, link, unlink }
