'use strict'

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

class Raffle {
  static findAll(tenantId) {
    if (tenantId) return query('SELECT * FROM raffles WHERE tenant_id=$1 ORDER BY data_criacao DESC', [tenantId])
    return query('SELECT * FROM raffles ORDER BY data_criacao DESC')
  }

  static findActive(tenantId) {
    if (tenantId) return query(
      "SELECT * FROM raffles WHERE ativo=1 AND status!='finished' AND tenant_id=$1 ORDER BY data_criacao DESC",
      [tenantId]
    )
    return query("SELECT * FROM raffles WHERE ativo=1 AND status!='finished' ORDER BY data_criacao DESC")
  }

  static findById(id) {
    return queryOne('SELECT * FROM raffles WHERE id = $1', [id])
  }

  static create({ titulo, descricao, preco_numero, total_numeros, start_at, end_at, tenant_id }) {
    return execute(
      `INSERT INTO raffles (titulo, descricao, preco_numero, total_numeros, start_at, end_at, tenant_id)
       VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id`,
      [titulo, descricao || null, preco_numero || 5.0, total_numeros || 500,
       start_at || null, end_at || null, tenant_id || 1]
    )
  }

  static update(id, { titulo, descricao, preco_numero, total_numeros, ativo, start_at, end_at }) {
    return execute(
      `UPDATE raffles SET titulo=$1, descricao=$2, preco_numero=$3, total_numeros=$4, ativo=$5, start_at=$6, end_at=$7
       WHERE id=$8`,
      [titulo, descricao, preco_numero, total_numeros, ativo, start_at || null, end_at || null, id]
    )
  }

  static finish(id) {
    return execute(`UPDATE raffles SET status='finished', ativo=0 WHERE id=$1`, [id])
  }

  static deleteById(id) {
    return execute('DELETE FROM raffles WHERE id = $1', [id])
  }
}

module.exports = Raffle
