'use strict'

const { execute, queryOne } = require('../database/postgres')

class RaffleFlashPromo {
  static getActive(raffleId) {
    return queryOne(
      `SELECT * FROM raffle_flash_promos
       WHERE raffle_id = $1 AND starts_at <= NOW() AND ends_at > NOW()
       ORDER BY ends_at DESC LIMIT 1`,
      [raffleId]
    )
  }

  static create({ raffle_id, discount_pct, label, duration_minutes }) {
    return execute(
      `INSERT INTO raffle_flash_promos (raffle_id, discount_pct, label, starts_at, ends_at)
       VALUES ($1, $2, $3, NOW(), NOW() + ($4 * INTERVAL '1 minute'))
       RETURNING *`,
      [raffle_id, parseFloat(discount_pct), label || 'Promoção Relâmpago', parseInt(duration_minutes)]
    )
  }

  static cancel(id) {
    return execute(
      `UPDATE raffle_flash_promos SET ends_at = NOW() WHERE id = $1`,
      [id]
    )
  }
}

module.exports = RaffleFlashPromo
