// Shared by every moderation command (ban/kick/mute/warn): writes the audit
// row and posts the embed to the configured mod-log channel. Takes `client`
// as a parameter (from interaction.client) rather than importing
// discordManager directly, to avoid a require cycle (discordManager -> commands
// -> modLog -> discordManager).
const { EmbedBuilder } = require('discord.js')

const db = require('../db')
const guildConfig = require('../model/guildConfig')
const createLogger = require('../utils/logger')

const log = createLogger('modlog')

const COLOR = { ban: 0xd98b84, kick: 0xe0b070, mute: 0xe0b070, warn: 0xe0b070 }

async function record({ client, guildId, actionType, target, staffUser, reason, durationSeconds }) {
  await db.query(
    `INSERT INTO mod_actions (guild_id, action_type, target_user_id, target_tag, staff_user_id, staff_tag, reason, duration_seconds)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
    [guildId, actionType, target.id, target.tag || null, staffUser.id, staffUser.tag || null, reason || null, durationSeconds || null],
  )

  try {
    const channelId = await guildConfig.getModLogChannelId(guildId)
    if (!channelId) return
    const channel = await client.channels.fetch(channelId)
    if (!channel || !channel.isTextBased()) return

    const embed = new EmbedBuilder()
      .setColor(COLOR[actionType] || 0x9aa5b1)
      .setTitle(actionType.toUpperCase())
      .addFields(
        { name: 'Target', value: `${target.tag || target.id} (${target.id})`, inline: true },
        { name: 'Staff', value: `${staffUser.tag || staffUser.id} (${staffUser.id})`, inline: true },
      )
      .setTimestamp()
    if (reason) embed.addFields({ name: 'Reason', value: reason })
    if (durationSeconds) embed.addFields({ name: 'Duration', value: formatDuration(durationSeconds), inline: true })

    await channel.send({ embeds: [embed] })
  } catch (err) {
    log.warn('failed to post mod-log embed', { message: err.message })
  }
}

// Post an "appeal approved → action reversed" embed to the mod-log channel.
// Unlike record() this NEVER inserts a mod_actions row — the reversal is an
// out-of-band correction driven by the site's appeals flow, not a new staff
// action. Best-effort: a missing channel or send failure is logged, not thrown.
async function postReversal({ client, guildId, actionType, discordUserId, appealId }) {
  try {
    const channelId = await guildConfig.getModLogChannelId(guildId)
    if (!channelId) return
    const channel = await client.channels.fetch(channelId)
    if (!channel || !channel.isTextBased()) return

    const reversed = actionType === 'ban' ? 'Ban lifted (unbanned)' : 'Mute cleared (timeout removed)'
    const embed = new EmbedBuilder()
      .setColor(0x88c0a0)
      .setTitle('APPEAL APPROVED')
      .addFields(
        { name: 'Action reversed', value: reversed, inline: true },
        { name: 'Target id', value: `${discordUserId}`, inline: true },
        { name: 'Appeal', value: `#${appealId}`, inline: true },
      )
      .setTimestamp()

    await channel.send({ embeds: [embed] })
  } catch (err) {
    log.warn('failed to post appeal-reversal embed', { message: err.message })
  }
}

function formatDuration(seconds) {
  if (seconds % 86400 === 0) return `${seconds / 86400}d`
  if (seconds % 3600 === 0) return `${seconds / 3600}h`
  if (seconds % 60 === 0) return `${seconds / 60}m`
  return `${seconds}s`
}

module.exports = { record, postReversal }
