import kotlin.Long;
import kotlin.collections.List;

CREATE TABLE categories(
    _id INTEGER NOT NULL PRIMARY KEY,
    name TEXT NOT NULL,
    sort INTEGER NOT NULL,
    flags INTEGER NOT NULL,
    manga_order TEXT AS List<Long> NOT NULL,
    -- KMK -->
    hidden INTEGER NOT NULL DEFAULT 0
    -- KMK <--
);

-- Insert system category
INSERT OR IGNORE INTO categories(_id, name, sort, flags, manga_order, hidden) VALUES (0, "", -1, 0, "", 0);
-- Disallow deletion of default category
CREATE TRIGGER IF NOT EXISTS system_category_delete_trigger BEFORE DELETE
ON categories
BEGIN SELECT CASE
    WHEN old._id <= 0 THEN
        RAISE(ABORT, "System category can't be deleted")
    END;
END;

getCategory:
SELECT _id,name,sort,flags,hidden
FROM categories
WHERE _id = :id
LIMIT 1;

getCategories:
SELECT
_id AS id,
name,
sort AS `order`,
flags,
-- KMK -->
hidden
-- KMK <--
FROM categories
ORDER BY sort;

getCategoriesByMangaId:
SELECT
C._id AS id,
C.name,
C.sort AS `order`,
C.flags,
-- KMK -->
C.hidden
-- KMK <--
FROM categories C
JOIN mangas_categories MC
ON C._id = MC.category_id
WHERE MC.manga_id = :mangaId;

insert:
INSERT INTO categories(name, sort, flags, manga_order, hidden)
VALUES (:name, :order, :flags, "", :hidden);

delete:
DELETE FROM categories
WHERE _id = :categoryId;

update:
UPDATE categories
SET name = coalesce(:name, name),
    sort = coalesce(:order, sort),
    flags = coalesce(:flags, flags),
    -- KMK -->
    hidden = coalesce(:hidden, hidden)
    -- KMK <--
WHERE _id = :categoryId;

updateAllFlags:
UPDATE categories SET
flags = coalesce(?, flags);

selectLastInsertedRowId:
SELECT last_insert_rowid();
