-- name: ListWords :many
SELECT w.id, w.category_id, w.word, w.translation, w.phonetic,
       w.example_sentence, w.audio_url, w.image_url, w.sort_order,
       w.created_at, w.updated_at
FROM words w
WHERE
    (@category_id::int = 0 OR w.category_id = @category_id)
    AND (@keyword::text = '' OR w.word ILIKE '%' || @keyword || '%' OR w.translation ILIKE '%' || @keyword || '%')
ORDER BY w.sort_order ASC, w.id ASC
LIMIT $1 OFFSET $2;

-- name: CountWords :one
SELECT COUNT(*) AS total
FROM words w
WHERE
    (@category_id::int = 0 OR w.category_id = @category_id)
    AND (@keyword::text = '' OR w.word ILIKE '%' || @keyword || '%' OR w.translation ILIKE '%' || @keyword || '%');

-- name: GetWord :one
SELECT id, category_id, word, translation, phonetic,
       example_sentence, audio_url, image_url, sort_order,
       created_at, updated_at
FROM words
WHERE id = $1;

-- name: CreateWord :one
INSERT INTO words (category_id, word, translation, phonetic, example_sentence, audio_url, image_url, sort_order)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id, category_id, word, translation, phonetic,
          example_sentence, audio_url, image_url, sort_order,
          created_at, updated_at;

-- name: UpdateWord :one
UPDATE words
SET category_id = $2,
    word = $3,
    translation = $4,
    phonetic = $5,
    example_sentence = $6,
    audio_url = $7,
    image_url = $8,
    sort_order = $9,
    updated_at = NOW()
WHERE id = $1
RETURNING id, category_id, word, translation, phonetic,
          example_sentence, audio_url, image_url, sort_order,
          created_at, updated_at;

-- name: DeleteWord :exec
DELETE FROM words WHERE id = $1;
