-- name: GetPost :many
SELECT id, content, signing, post_at, heart, igid, array_agg(url) as enclosure
FROM posts 
LEFT JOIN media ON post_id is not null AND post_id = id AND visible
WHERE phase = 'ok'
GROUP BY id
ORDER BY id DESC 
LIMIT $1;

-- name: GetPostWithCursor :many
SELECT id, content, signing, post_at, heart, igid, array_agg(url) as enclosure
FROM posts 
LEFT JOIN media ON post_id is not null AND post_id = id AND visible
WHERE id <= $1 AND phase = 'ok'
GROUP BY id
ORDER BY id DESC 
LIMIT $2;

-- name: InsertPost :one
INSERT INTO posts (content,signing,hash) 
VALUES ($1, $2 ,$3) 
RETURNING id,hash;

-- name: UpdatePostIGID :exec
UPDATE posts set igid = $1 WHERE id = $2;

-- name: DeletePost :exec
UPDATE posts SET phase = 'deleted' WHERE id = $1 AND hash=$2;

-- name: InvalidateMedia :exec
UPDATE media SET visible = false WHERE post_id = $1;

-- name: GetComment :many
SELECT id, content, signing, post_at 
FROM comment 
WHERE phase = 'ok' AND post_id = $1
ORDER BY id DESC 
LIMIT $2;

-- name: GetCommentWithCursor :many
SELECT id, content, signing, post_at 
FROM comment
WHERE id <= $1 AND phase = 'ok' AND post_id = $2
ORDER BY id DESC 
LIMIT $3;


-- name: InsertPostImage :exec
INSERT INTO media (url, post_id) VALUES ($1, $2);

-- name: InsertCommentImage :exec
INSERT INTO media (url, comment_id) VALUES ($1, $2);

-- name: AddPostHeart :one
UPDATE posts SET heart = heart + 1 WHERE id=$1 RETURNING heart;

-- name: AddCommentHeart :one
UPDATE comment SET heart = heart + 1 WHERE id=$1 RETURNING heart;

-- name: AdminGetPost :many
SELECT id, content, signing, post_at FROM posts WHERE phase = 'pending' ORDER BY id DESC LIMIT 100;

-- name: SuperAdminGetPost :many
SELECT id, content, signing, post_at, phase FROM posts WHERE phase = 'pending' OR phase = 'rejected' ORDER BY id DESC LIMIT 100;

-- name: AdminGetMedia :many
SELECT url from media WHERE post_id = $1;

-- name: AdminVerify :one
UPDATE posts SET phase = $1 WHERE id=$2 AND phase = 'pending' RETURNING id;

-- name: SuperAdminVerify :one
UPDATE posts SET phase = $1 WHERE id=$2 AND (phase = 'pending' OR phase = 'rejected') RETURNING id;

-- name: AdminUpdateImage :exec
UPDATE media SET visible = true WHERE post_id=$1;

-- name: AdminLoginGetTOTP :one
SELECT totp, super FROM admin WHERE username = $1 AND password = $2;

-- name: AdminCreateAccount :exec
INSERT INTO admin (username, password, totp) VALUES ($1, $2,$3);
