'use strict'

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

class RaffleDiscount {
  static listByRaffle(raffleId) {
    return query(
      `SELECT id, min_qty, discount_pct, active
       FROM raffle_discounts
       WHERE raffle_id = $1
       ORDER BY min_qty ASC`,
      [raffleId]
    )
  }

  // Returns the best (highest) active discount for the given quantity
  static getBestForQty(raffleId, qty) {
    return queryOne(
      `SELECT id, min_qty, discount_pct
       FROM raffle_discounts
       WHERE raffle_id = $1 AND min_qty <= $2 AND active = TRUE
       ORDER BY discount_pct DESC
       LIMIT 1`,
      [raffleId, qty]
    )
  }

  // Returns the next discount tier above current qty (for "buy X more" hint)
  static getNextTier(raffleId, qty) {
    return queryOne(
      `SELECT id, min_qty, discount_pct
       FROM raffle_discounts
       WHERE raffle_id = $1 AND min_qty > $2 AND active = TRUE
       ORDER BY min_qty ASC
       LIMIT 1`,
      [raffleId, qty]
    )
  }

  static deleteByRaffle(raffleId) {
    return execute('DELETE FROM raffle_discounts WHERE raffle_id = $1', [raffleId])
  }

  static bulkInsert(raffleId, tiers) {
    if (!tiers || tiers.length === 0) return Promise.resolve()
    const values = tiers
      .map((t, i) => `($1, $${i * 2 + 2}, $${i * 2 + 3}, TRUE)`)
      .join(', ')
    const params = [raffleId, ...tiers.flatMap(t => [parseInt(t.min_qty), parseFloat(t.discount_pct)])]
    return execute(
      `INSERT INTO raffle_discounts (raffle_id, min_qty, discount_pct, active) VALUES ${values}`,
      params
    )
  }
}

module.exports = RaffleDiscount
