'use strict'

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

class Claim {
  static async create({ raffle_id, ticket_id, user_cpf, delivery_address, delivery_notes }) {
    return execute(
      `INSERT INTO raffle_claims (raffle_id, ticket_id, user_cpf, delivery_address, delivery_notes)
       VALUES ($1, $2, $3, $4, $5) RETURNING id`,
      [raffle_id, ticket_id, user_cpf, delivery_address || null, delivery_notes || null]
    )
  }

  static async getUserClaims(user_cpf) {
    return query(
      `SELECT c.*, r.titulo as raffle_titulo, t.numero as ticket_numero 
       FROM raffle_claims c
       JOIN raffles r ON r.id = c.raffle_id
       JOIN tickets t ON t.id = c.ticket_id
       WHERE c.user_cpf = $1
       ORDER BY c.claimed_at DESC`,
      [user_cpf]
    )
  }

  static async getClaimDetails(id) {
    return queryOne(
       `SELECT c.*, r.titulo as raffle_titulo, t.numero as ticket_numero 
       FROM raffle_claims c
       JOIN raffles r ON r.id = c.raffle_id
       JOIN tickets t ON t.id = c.ticket_id
       WHERE c.id = $1`,
      [id]
    )
  }

  static async updateStatus(id, status) {
    return execute(
      `UPDATE raffle_claims SET status = $1, updated_at = NOW()
       WHERE id = $2`,
      [status, id]
    )
  }
}

module.exports = Claim
