CREATE TABLE sources (
    id      BIGINT       PRIMARY KEY,
    name    VARCHAR(128) NOT NULL,
    lang    VARCHAR(32)  NOT NULL,
    is_nsfw BOOLEAN      NOT NULL DEFAULT FALSE
);

CREATE TABLE manga (
    id                       SERIAL        PRIMARY KEY,
    source_id                BIGINT        NOT NULL REFERENCES sources(id),
    url                      VARCHAR(2048) NOT NULL,
    title                    VARCHAR(512)  NOT NULL,
    initialized              BOOLEAN       NOT NULL DEFAULT FALSE,
    artist                   TEXT,
    author                   TEXT,
    description              TEXT,
    genre                    TEXT,
    status                   INTEGER       NOT NULL DEFAULT 0,
    thumbnail_url            VARCHAR(2048),
    thumbnail_last_fetched   BIGINT        NOT NULL DEFAULT 0,
    in_library               BOOLEAN       NOT NULL DEFAULT FALSE,
    in_library_at            BIGINT        NOT NULL DEFAULT 0,
    real_url                 VARCHAR(2048),
    last_fetched_at          BIGINT        NOT NULL DEFAULT 0,
    chapters_last_fetched_at BIGINT        NOT NULL DEFAULT 0,
    update_strategy          VARCHAR(64)   NOT NULL DEFAULT 'ALWAYS_UPDATE',
    UNIQUE (source_id, url)
);

CREATE INDEX ON manga (source_id);
CREATE INDEX ON manga (last_fetched_at);

CREATE TABLE chapters (
    id             SERIAL        PRIMARY KEY,
    manga_id       INTEGER       NOT NULL REFERENCES manga(id) ON DELETE CASCADE,
    url            VARCHAR(2048) NOT NULL,
    name           VARCHAR(512)  NOT NULL,
    date_upload    BIGINT        NOT NULL DEFAULT 0,
    chapter_number REAL          NOT NULL DEFAULT -1,
    scanlator      VARCHAR(256),
    source_order   INTEGER       NOT NULL,
    is_read        BOOLEAN       NOT NULL DEFAULT FALSE,
    is_bookmarked  BOOLEAN       NOT NULL DEFAULT FALSE,
    last_page_read INTEGER       NOT NULL DEFAULT 0,
    last_read_at   BIGINT        NOT NULL DEFAULT 0,
    fetched_at     BIGINT        NOT NULL DEFAULT 0,
    real_url       VARCHAR(2048),
    is_downloaded  BOOLEAN       NOT NULL DEFAULT FALSE,
    page_count     INTEGER       NOT NULL DEFAULT -1,
    UNIQUE (manga_id, url)
);

CREATE INDEX ON chapters (manga_id);

CREATE TABLE pages (
    id         SERIAL        PRIMARY KEY,
    chapter_id INTEGER       NOT NULL REFERENCES chapters(id) ON DELETE CASCADE,
    "index"    INTEGER       NOT NULL,
    url        VARCHAR(2048) NOT NULL,
    image_url  TEXT,
    UNIQUE (chapter_id, "index")
);

CREATE INDEX ON pages (chapter_id);

CREATE TABLE source_meta (
    source_id BIGINT       NOT NULL REFERENCES sources(id),
    key       VARCHAR(256) NOT NULL,
    value     TEXT         NOT NULL,
    PRIMARY KEY (source_id, key)
);
