// Staff notes on a Discord user (server-owned, see db/schema.sql mod_notes).
// Notes are never user-visible; admin_only notes are filtered out for non-admin
// callers at this layer via includeAdminOnly.
const { query } = require('../../utils/db')

async function listForUser(discordId, { includeAdminOnly = false } = {}) {
  const visClause = includeAdminOnly ? '' : "AND n.visibility = 'staff_only'"
  return query(
    `SELECT n.id, n.discord_user_id, n.author_user_id, n.author_tag,
            n.body, n.visibility, n.created_at,
            u.username AS author_username
       FROM mod_notes n
       LEFT JOIN users u ON u.id = n.author_user_id
      WHERE n.discord_user_id = ? ${visClause}
      ORDER BY n.id DESC`,
    [discordId],
  )
}

async function insert({ discordUserId, authorUserId = null, authorTag = null, body, visibility = 'staff_only' }) {
  const res = await query(
    `INSERT INTO mod_notes (discord_user_id, author_user_id, author_tag, body, visibility)
     VALUES (?, ?, ?, ?, ?)`,
    [discordUserId, authorUserId, authorTag, body, visibility],
  )
  return res.insertId
}

async function getById(id) {
  const rows = await query(
    `SELECT n.id, n.discord_user_id, n.author_user_id, n.author_tag,
            n.body, n.visibility, n.created_at,
            u.username AS author_username
       FROM mod_notes n
       LEFT JOIN users u ON u.id = n.author_user_id
      WHERE n.id = ? LIMIT 1`,
    [id],
  )
  return rows[0] || null
}

async function countForUser(discordId, { includeAdminOnly = false } = {}) {
  const visClause = includeAdminOnly ? '' : "AND visibility = 'staff_only'"
  const rows = await query(
    `SELECT COUNT(*) AS c FROM mod_notes WHERE discord_user_id = ? ${visClause}`,
    [discordId],
  )
  return Number(rows[0].c)
}

module.exports = { listForUser, insert, getById, countForUser }
