-- name: CreateUserBonus :one
INSERT INTO user_bonuses (
        name,
        description,
        type,
        user_id,
        reward_amount,
        expires_at
    )
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING *;
-- name: GetAllUserBonuses :many 
SELECT *
FROM user_bonuses
WHERE (
        user_id = sqlc.narg('user_id')
        OR sqlc.narg('user_id') IS NULL
    )
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: GetUserBonusByID :one
SELECT *
FROM user_bonuses
WHERE id = $1;

-- name: GetBonusCount :one
SELECT COUNT(*)
FROM user_bonuses
WHERE (
        user_id = sqlc.narg('user_id')
        OR sqlc.narg('user_id') IS NULL
    );
-- name: GetBonusStats :one
SELECT COUNT(*) AS total_bonuses,
    COALESCE(SUM(reward_amount), 0)::bigint AS total_reward_earned,
    COUNT(
        CASE
            WHEN is_claimed = true THEN 1
        END
    ) AS claimed_bonuses,
    COUNT(
        CASE
            WHEN expires_at < now() THEN 1
        END
    ) AS expired_bonuses
FROM user_bonuses
    JOIN users ON users.id = user_bonuses.user_id
WHERE (
        company_id = sqlc.narg('company_id')
        OR sqlc.narg('company_id') IS NULL
    )
    AND (
        user_id = sqlc.narg('user_id')
        OR sqlc.narg('user_id') IS NULL
    );
-- name: UpdateUserBonus :exec
UPDATE user_bonuses
SET is_claimed = $2
WHERE id = $1;
-- name: DeleteUserBonus :exec
DELETE FROM user_bonuses
WHERE id = $1;