-- name: GetPostsByPostId :one
SELECT *
FROM public.posts posts
where posts.post_id = $1;

-- name: GetPostsByUserId :many
SELECT *
FROM public.posts posts
where posts.user_id = $1;

-- name: GetPostsByBlogId :many
SELECT *
FROM public.posts posts 
where posts.blog_id = $1;

-- name: CreatePost :one
INSERT INTO public.posts
(post_id, blog_id, user_id, title, "content", created_at, updated_at)
VALUES($1, $2, $3, $4, $5, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
RETURNING *;

-- name: UpdatePostByPostId :one
UPDATE public.posts
SET title=$1, "content"=$2, updated_at=CURRENT_TIMESTAMP
WHERE post_id = $3
RETURNING *;

-- name: DeletePostByPostId :exec
DELETE FROM public.posts
WHERE post_id=$1;

-- name: UpdatePostBlogId :exec
UPDATE public.posts
SET blog_id=$2, updated_at=CURRENT_TIMESTAMP
WHERE post_id = $1
RETURNING *;

-- name: GetRandomPosts :one
WITH all_posts AS (
  SELECT 
    COUNT(*) AS post_count 
  FROM 
    public.posts
), 
filtered_posts AS (
  SELECT 
    ARRAY(
      SELECT 
        json_build_object(
          'post_id', post_id::text, 'blog_id', blog_id::text, 
          'user_id', user_id::text, 'title', title, 
          'created_at', created_at, 'content', SUBSTRING(content FROM 1 FOR 300)
        ) 
      FROM 
        public.posts 
      ORDER BY 
        created_at DESC 
      LIMIT $1 OFFSET $3
    ) as selected_posts
) 
SELECT 
  fp.selected_posts,
  (ap.post_count - ($2 + 1) * $1)::int > 0 as has_next_page,
  case
    when (ap.post_count - ($2 + 1) * $1)::int > 0
    then $2 + 1
    else -1
  end as next_page_index,
  case
    when (ap.post_count  - ( $2 + 1 ) * $1 + 1 * $1)::int <= ap.post_count
    then $2 - 1
    else -1
  end as prev_page_index
FROM 
  filtered_posts fp, 
  all_posts ap;
