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

async function addRecurring({ guildId, channelId, content, cronExpression, createdBy, createdByTag }) {
  const res = await db.query(
    `INSERT INTO scheduled_messages (guild_id, channel_id, content, cron_expression, created_by, created_by_tag)
     VALUES (?, ?, ?, ?, ?, ?)`,
    [guildId, channelId, content, cronExpression, createdBy || null, createdByTag || null],
  )
  return res.insertId
}

async function addOnce({ guildId, channelId, content, runAt, createdBy, createdByTag }) {
  const res = await db.query(
    `INSERT INTO scheduled_messages (guild_id, channel_id, content, run_at, created_by, created_by_tag)
     VALUES (?, ?, ?, ?, ?, ?)`,
    [guildId, channelId, content, runAt, createdBy || null, createdByTag || null],
  )
  return res.insertId
}

// Returns true if a row was actually removed (scoped to the guild so one
// guild can't remove another's rows).
async function remove(guildId, id) {
  const res = await db.query('DELETE FROM scheduled_messages WHERE id = ? AND guild_id = ?', [id, guildId])
  return Number(res.affectedRows || 0) > 0
}

async function list(guildId) {
  return db.query(
    `SELECT id, channel_id, content, cron_expression, run_at, enabled, sent_at FROM scheduled_messages
     WHERE guild_id = ? ORDER BY id ASC`,
    [guildId],
  )
}

// All enabled recurring rows across every guild the bot serves — v1 only
// ever has one, but the scheduler doesn't need to special-case that.
async function listEnabledRecurring() {
  return db.query(
    `SELECT id, guild_id, channel_id, content, cron_expression FROM scheduled_messages
     WHERE cron_expression IS NOT NULL AND enabled = 1`,
  )
}

// One-off rows due to post right now.
async function listDueOneOff() {
  return db.query(
    `SELECT id, guild_id, channel_id, content FROM scheduled_messages
     WHERE run_at IS NOT NULL AND sent_at IS NULL AND enabled = 1 AND run_at <= NOW()`,
  )
}

async function markSent(id) {
  await db.query('UPDATE scheduled_messages SET sent_at = NOW() WHERE id = ?', [id])
}

module.exports = { addRecurring, addOnce, remove, list, listEnabledRecurring, listDueOneOff, markSent }
