-- name: CreateRaffle :one
INSERT INTO raffles (company_id, name, expires_at, type)
VALUES ($1, $2, $3, $4)
RETURNING *;

-- name: GetRafflesOfCompany :many
SELECT * FROM raffles WHERE company_id = $1;

-- name: DeleteRaffle :one
DELETE FROM raffles
WHERE id = $1
RETURNING *;

-- name: UpdateRaffleTicketStatus :exec
UPDATE raffle_tickets
SET is_active = $1
WHERE id = $2;

-- name: CreateRaffleTicket :one
INSERT INTO raffle_tickets (raffle_id, user_id)
VALUES ($1, $2)
RETURNING *;

-- name: GetUserRaffleTickets :many
SELECT 
    rt.id AS ticket_id,
    rt.user_id,
    r.name,
    r.type,
    r.expires_at,
    r.status
FROM raffle_tickets rt
JOIN raffles r ON rt.raffle_id = r.id
WHERE rt.user_id = $1;

-- name: GetRaffleStanding :many
SELECT
    u.id AS user_id,
    rt.raffle_id,
    u.first_name,
    u.last_name,
    u.phone_number,
    u.email,
    COUNT(*) AS ticket_count
FROM raffle_tickets rt
JOIN users u ON rt.user_id = u.id
WHERE rt.is_active = true
  AND rt.raffle_id = $1
GROUP BY u.id, rt.raffle_id, u.first_name, u.last_name, u.phone_number, u.email
ORDER BY ticket_count DESC
LIMIT $2;

-- name: CreateRaffleWinner :one
INSERT INTO raffle_winners (raffle_id, user_id, rank)
VALUES ($1, $2, $3)
RETURNING *;

-- name: SetRaffleComplete :exec
UPDATE raffles
SET status = 'completed'
WHERE id = $1;
