'use strict'

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

class PriceRule {
  static async create({ raffle_id, rule_type, price, start_at, end_at, priority }) {
    return execute(
      `INSERT INTO raffle_price_rules (raffle_id, rule_type, price, start_at, end_at, priority)
       VALUES ($1, $2, $3, $4, $5, $6) RETURNING id`,
      [raffle_id, rule_type, price, start_at || null, end_at || null, priority || 0]
    )
  }

  static async listByRaffle(raffle_id) {
    return query(
      `SELECT * FROM raffle_price_rules WHERE raffle_id = $1 AND active = 1 ORDER BY priority DESC`,
      [raffle_id]
    )
  }

  /**
   * Engine de Preço Dinâmico: Verifica qual regra está ativa agora.
   * Retorna o preço apropriado e o ID da regra aplicada (se houver).
   */
  static async getCurrentPrice(raffle_id) {
    const rules = await this.listByRaffle(raffle_id)
    const now = new Date()

    let appliedRuleId = null

    for (const rule of rules) {
      if (rule.rule_type === 'time_range') {
        const start = rule.start_at ? new Date(rule.start_at) : new Date(0)
        const end = rule.end_at ? new Date(rule.end_at) : new Date(8640000000000000) // max date
        if (now >= start && now <= end) {
          return { price: parseFloat(rule.price), rule_id: rule.id }
        }
      }

      if (rule.rule_type === 'fixed') {
        return { price: parseFloat(rule.price), rule_id: rule.id }
      }
    }

    // Fallback: Busca o preço padrão do sorteio
    const raffle = await Raffle.findById(raffle_id)
    if (!raffle) throw new Error('Sorteio não encontrado')

    return { price: parseFloat(raffle.preco_numero), rule_id: null }
  }

  static async logPrice({ raffle_id, order_id, user_cpf, price_applied, rule_id }) {
    return execute(
      `INSERT INTO price_logs (raffle_id, order_id, user_cpf, price_applied, rule_id)
       VALUES ($1, $2, $3, $4, $5)`,
      [raffle_id, order_id || null, user_cpf || null, price_applied, rule_id || null]
    )
  }
}

module.exports = PriceRule
