const { query } = require('../../utils/db')

// Find the identity row for an external (provider, subject) pair. This is the
// link-only login lookup: no row → no account → login refused.
async function findByProviderSubject(provider, subject) {
  const rows = await query(
    'SELECT * FROM user_identities WHERE provider = ? AND subject = ? LIMIT 1',
    [provider, subject],
  )
  return rows[0] || null
}

// All identities linked to a given internal user (for the Account page).
async function listForUser(userId) {
  return query(
    'SELECT id, provider, subject, email, created_at FROM user_identities WHERE user_id = ? ORDER BY provider',
    [userId],
  )
}

async function insert({ userId, provider, subject, email = null }) {
  const res = await query(
    'INSERT INTO user_identities (user_id, provider, subject, email) VALUES (?, ?, ?, ?)',
    [userId, provider, subject, email],
  )
  return res.insertId
}

// Remove a user's link to a provider. Returns rows deleted.
async function deleteForUserProvider(userId, provider) {
  const res = await query(
    'DELETE FROM user_identities WHERE user_id = ? AND provider = ?',
    [userId, provider],
  )
  return Number(res.affectedRows || 0)
}

module.exports = { findByProviderSubject, listForUser, insert, deleteForUserProvider }
