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

async function record({ guildId, channelId, inviteCode, triggeredBy, triggeredByTag }) {
  const res = await db.query(
    `INSERT INTO invite_log (guild_id, channel_id, invite_code, triggered_by, triggered_by_tag)
     VALUES (?, ?, ?, ?, ?)`,
    [guildId, channelId, inviteCode, triggeredBy || null, triggeredByTag || null],
  )
  return res.insertId
}

// The active (not-yet-revoked) invite for a guild, if any.
async function getCurrent(guildId) {
  const rows = await db.query(
    'SELECT * FROM invite_log WHERE guild_id = ? AND revoked_at IS NULL ORDER BY created_at DESC LIMIT 1',
    [guildId],
  )
  return rows[0] || null
}

async function markRevoked(id) {
  await db.query('UPDATE invite_log SET revoked_at = NOW() WHERE id = ?', [id])
}

async function list(guildId, limit = 10) {
  return db.query('SELECT * FROM invite_log WHERE guild_id = ? ORDER BY created_at DESC LIMIT ?', [guildId, limit])
}

module.exports = { record, getCurrent, markRevoked, list }
