-- :name create-image! :i!
INSERT INTO images (hash, title, description)
VALUES (:hash, :title, :description)

-- :name update-image! :! :n
UPDATE images
SET hash = :hash, title = :title, description = :description
WHERE id = :id

-- :name get-image :? :1
SELECT * FROM images WHERE id = :id

-- :name delete-image! :! :n
DELETE FROM images
WHERE id = :id

-- :name get-all-images :? :*
SELECT * FROM images
ORDER BY created_at DESC
LIMIT :count OFFSET :offset

-- :name get-image-count :? :1
SELECT COUNT(id) as count FROM images

-- :name get-next-image :? :1
SELECT * FROM images
WHERE created_at > :image-date
ORDER BY created_at ASC
LIMIT 1

-- :name get-prev-image :? :1
SELECT * FROM images
WHERE created_at < :image-date
ORDER BY created_at DESC
LIMIT 1

-- :name edit-image! :! :1
UPDATE images
SET title = :title, description = :description
WHERE id = :id

-- :name set-image-hash :! :1
UPDATE images
SET hash = :hash
WHERE id = :id

-- :name get-first-year :? :1
SELECT created_at FROM images
ORDER BY created_at ASC
LIMIT 1

-- :name get-recent-year :? :1
SELECT created_at FROM images
ORDER BY created_at DESC
LIMIT 1

-- :name create-tag! :i!
INSERT OR IGNORE INTO tags (tagname)
VALUES (:tagname)

-- :name add-tag-to-image! :!
INSERT OR IGNORE INTO image_tags (image_id, tag_id)
VALUES (:imageid, :tagid)

-- :name delete-image-tags! :!
DELETE FROM image_tags
WHERE image_id = :id

-- :name get-tag :? :1
SELECT * FROM tags
WHERE tagname = :tagname

-- :name get-tags-for-image :? :*
SELECT tags.tagname FROM image_tags
INNER JOIN tags ON tags.id = image_tags.tag_id
WHERE image_id = :id
ORDER BY tags.tagname ASC

-- :name get-images-for-tagname :? :*
SELECT images.* FROM image_tags
INNER JOIN images ON images.id = image_tags.image_id
INNER JOIN tags on tags.id = image_tags.tag_id
WHERE tags.tagname = :tagname
ORDER BY images.created_at DESC


-- :name create-comment! :! :n
INSERT INTO comments (image_id, author, comment)
VALUES (:image_id, :author, :comment)

-- :name get-comments-for-image :? :*
SELECT * FROM comments
WHERE image_id = :image_id
ORDER BY created_at ASC

-- :name get-comment :? :1
SELECT * FROM comments
WHERE id = :id
LIMIT 1

-- :name delete-comment! :! :1
DELETE FROM comments
WHERE id = :id

-- :name get-recent-comments :? :*
SELECT comments.*, images.title FROM comments
LEFT JOIN images ON images.id = comments.image_id
ORDER BY created_at DESC
LIMIT :num-comments

-- :name delete-image-comments! :!
DELETE FROM comments
WHERE image_id = :id
