-- name: CreateUser :one
INSERT INTO users (email, username, password_hash)
VALUES ($1, $2, $3)
RETURNING *;

-- name: GetUserByEmail :one
SELECT * FROM users WHERE email = $1;

-- name: GetUserByUsername :one
SELECT * FROM users WHERE username = $1;

-- name: GetUserByEmailOrUsername :one
SELECT * FROM users WHERE email = $1 OR username = $1;

-- name: GetUser :one
SELECT id, email, username, created_at, updated_at FROM users WHERE id = $1;

-- name: GetEbook :one
SELECT * FROM ebooks WHERE id = $1;

-- name: ListEbooks :many
SELECT * FROM ebooks ORDER BY created_at DESC LIMIT $1 OFFSET $2;

-- name: CreateEbook :one
INSERT INTO ebooks (title, author, isbn, description, file_path, file_size, mime_type, cover_image_path)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING *;

-- name: UpdateEbook :one
UPDATE ebooks SET
    title = $2,
    author = $3,
    isbn = $4,
    description = $5,
    cover_image_path = $6,
    updated_at = NOW()
WHERE id = $1
RETURNING *;

-- name: DeleteEbook :exec
DELETE FROM ebooks WHERE id = $1;

-- name: GetReadingProgress :one
SELECT * FROM reading_progress WHERE ebook_id = $1 AND user_id = $2;

-- name: UpdateReadingProgress :one
INSERT INTO reading_progress (ebook_id, user_id, current_page, total_pages, last_read_at)
VALUES ($1, $2, $3, $4, NOW())
ON CONFLICT (ebook_id, user_id)
DO UPDATE SET
    current_page = EXCLUDED.current_page,
    total_pages = EXCLUDED.total_pages,
    last_read_at = NOW()
RETURNING *;

-- name: DeleteReadingProgress :exec
DELETE FROM reading_progress WHERE ebook_id = $1 AND user_id = $2;