-- name: GetUtmsByID :many
-- SELECT ID,AmoFieldID,QuizID,AccountID,Name
-- FROM utms
-- WHERE
--     ID = ANY($1::int[]) AND Deleted = FALSE;
--

-- name: UpdateUtms :exec
-- UPDATE utms AS u
-- SET name = (update_data ->> 'Name')::varchar(512),
--     AmoFieldID = (update_data ->> 'AmoFieldID')::INT
-- FROM json_array_elements($1::json) AS update_data
-- WHERE u.ID = (update_data ->> 'ID')::INT;

-- name: UpdateUtmsFields :exec
-- UPDATE utms AS u SET AmoFieldID = f.AmoID FROM fields AS f
-- WHERE u.Name = f.Name AND u.ID = ANY($1::int[]) AND u.Deleted = FALSE;

-- name: DeletingUTM :exec
-- UPDATE utms SET Deleted = true WHERE ID = ANY($1::int[]);

-- name: GetUTMsWithPagination :many
-- SELECT ut.*, COUNT(*) OVER() as total_count
-- FROM utms ut JOIN (SELECT AmoID FROM users WHERE users.AccountID = $1) u ON ut.AccountID = u.AmoID
-- WHERE ut.Deleted = false and ut.QuizID = $4
-- ORDER BY ut.ID OFFSET ($2 - 1) * $3 LIMIT $3;

-- name: SaveUTMs :many
-- WITH user_data AS (
--     SELECT AmoID
--     FROM users
--     WHERE users.AccountID = $1
-- ), new_UTMs AS (
--     SELECT (utm->>'AmoFieldID')::INT AS amoFieldID,
--            COALESCE(utm->>'QuizID', '')::INT AS quizID,
--            COALESCE(utm->>'Name', '')::varchar(512) AS name,
--            CURRENT_TIMESTAMP AS createdAt
--     FROM json_array_elements($2::json) AS utm
-- ), inserted_utms AS(
--     INSERT INTO utms (AmoFieldID, QuizID, AccountID, Name, createdAt)
--         SELECT nu.amoFieldID,
--                nu.quizID,
--                ud.AmoID,
--                nu.name,
--                nu.createdAt
--         FROM new_UTMs nu
--                  JOIN user_data ud ON true
--         RETURNING *
-- )
-- SELECT * from inserted_utms;
