-- name: SelectCategoriesOfSite :many
SELECT * FROM categories
WHERE site_id = ? ORDER BY name ASC;

-- name: SelectCategory :one
SELECT * FROM categories WHERE id = ? LIMIT 1;

-- name: SelectCategoryByGUID :one
SELECT * FROM categories WHERE guid = ? LIMIT 1;

-- name: SelectCategoryBySlugAndSite :one
SELECT * FROM categories WHERE site_id = ? AND slug = ? LIMIT 1;

-- name: SelectCategoriesOfPost :many
SELECT c.* FROM categories c
INNER JOIN post_categories pc ON pc.category_id = c.id
WHERE pc.post_id = ?
ORDER BY c.name ASC;

-- name: SelectPostsOfCategory :many
SELECT p.* FROM posts p
INNER JOIN post_categories pc ON pc.post_id = p.id
WHERE pc.category_id = ? AND p.state = 0 AND p.deleted_at = 0
ORDER BY p.published_at DESC
LIMIT ? OFFSET ?;

-- name: CountPostsOfCategory :one
SELECT COUNT(*) FROM posts p
INNER JOIN post_categories pc ON pc.post_id = p.id
WHERE pc.category_id = ? AND p.state = 0 AND p.deleted_at = 0;

-- name: InsertCategory :one
INSERT INTO categories (
    site_id, guid, name, slug, description, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?)
RETURNING id;

-- name: UpdateCategory :exec
UPDATE categories SET
    name = ?,
    slug = ?,
    description = ?,
    updated_at = ?
WHERE id = ?;

-- name: DeleteCategory :exec
DELETE FROM categories WHERE id = ?;

-- name: InsertPostCategory :exec
INSERT OR IGNORE INTO post_categories (post_id, category_id) VALUES (?, ?);

-- name: DeletePostCategoriesByPost :exec
DELETE FROM post_categories WHERE post_id = ?;
