// Once-a-minute sweep for expired temp_roles: removes the Discord role (best
// effort — the member/guild/role may already be gone) then deletes the row
// regardless, so a stale row can never block future re-grants of the same
// role to the same member.
const cron = require('node-cron')

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

const log = createLogger('temproles')

let client = null
let task = null

async function sweep() {
  try {
    const expired = await tempRoles.listExpired()
    for (const row of expired) {
      try {
        const guild = await client.guilds.fetch(row.guild_id)
        const member = await guild.members.fetch(row.user_id).catch(() => null)
        if (member) await member.roles.remove(row.role_id).catch(() => {})
      } catch (err) {
        log.warn('failed to remove expired temp role', { message: err.message, roleId: row.role_id, userId: row.user_id })
      } finally {
        await tempRoles.removeById(row.id)
      }
    }
  } catch (err) {
    log.error('temp role sweep failed', { message: err.message })
  }
}

function start(discordClient) {
  client = discordClient
  task = cron.schedule('* * * * *', sweep)
  log.info('temp role sweeper started')
}

function stop() {
  if (task) {
    task.stop()
    task = null
  }
  client = null
}

module.exports = { start, stop }
