-- name: AppFlagsCreateGame :one
INSERT INTO app_flags_games (uid, tags, question_amount, seconds)
VALUES ($1, $2, $3, $4)
RETURNING game_id, game_seed;

-- name: AppFlagsCreateGameWithSeed :one
INSERT INTO app_flags_games (uid, tags, question_amount, seconds, game_seed)
VALUES ($1, $2, $3, $4, $5)
RETURNING game_id;

-- name: AppFlagsGetGame :one
SELECT * FROM app_flags_games WHERE game_id = $1 LIMIT 1;

-- name: AppFlagsUpdateGame :exec
UPDATE app_flags_games
SET question_current = $1, last_activity = CURRENT_TIMESTAMP
WHERE game_id = $2;

-- name: AppFlagsUpdateQuestionCorrect :exec
UPDATE app_flags_games
SET questions_errors = (
    SELECT COALESCE(SUM(errors), 0)
    FROM app_flags_games_answers
    WHERE app_flags_games_answers.game_id = app_flags_games.game_id
), last_activity = CURRENT_TIMESTAMP
WHERE app_flags_games.game_id = $1;

-- name: AppFlagsUpsertGameAnswer :exec
INSERT INTO app_flags_games_answers (game_id, question, errors)
VALUES ($1, $2, $3)
    ON CONFLICT (game_id, question)
DO UPDATE SET errors = app_flags_games_answers.errors + EXCLUDED.errors;

-- name: AppFlagsNewSharedData :one
INSERT INTO app_flags_games_shared_data (uid, share_key, game_seed, tags, questions, seconds) VALUES ($1, $2, $3, $4, $5, $6) RETURNING game_seed;

-- name: AppFlagsGetSharedData :one
SELECT * FROM app_flags_games_shared_data WHERE share_key = $1 LIMIT 1;

