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

const COLS =
  'id, token_hash, email, role, status, invited_by, accepted_user_id, expires_at, created_at, accepted_at'

async function insert({ tokenHash, email, role, invitedBy, expiresAt }) {
  const res = await query(
    `INSERT INTO user_invites (token_hash, email, role, invited_by, expires_at)
     VALUES (?, ?, ?, ?, ?)`,
    [tokenHash, email, role, invitedBy ?? null, expiresAt],
  )
  return res.insertId
}

async function getById(id) {
  const rows = await query(`SELECT ${COLS} FROM user_invites WHERE id = ? LIMIT 1`, [id])
  return rows[0] || null
}

async function findByTokenHash(tokenHash) {
  const rows = await query(`SELECT ${COLS} FROM user_invites WHERE token_hash = ? LIMIT 1`, [tokenHash])
  return rows[0] || null
}

const listRecent = (limit) =>
  query(`SELECT ${COLS} FROM user_invites ORDER BY created_at DESC LIMIT ?`, [limit])

// Mark accepted only if still pending (atomic guard against a double-accept race).
// Returns rows changed (1 = we won, 0 = already used/revoked).
async function markAccepted(id, userId) {
  const res = await query(
    `UPDATE user_invites SET status = 'accepted', accepted_user_id = ?, accepted_at = NOW()
      WHERE id = ? AND status = 'pending'`,
    [userId, id],
  )
  return res.affectedRows || 0
}

async function revoke(id) {
  const res = await query(
    `UPDATE user_invites SET status = 'revoked' WHERE id = ? AND status = 'pending'`,
    [id],
  )
  return res.affectedRows || 0
}

module.exports = { insert, getById, findByTokenHash, listRecent, markAccepted, revoke }
