-- articles
CREATE TABLE IF NOT EXISTS Articles
(
    id          INTEGER PRIMARY KEY NOT NULL,
    uuid        TEXT UNIQUE         NOT NULL, -- UUID
    stock       INTEGER             NOT NULL DEFAULT 0,
    name        TEXT                NOT NULL,
    description TEXT                NULL,     --in html
    price100    INTEGER             NOT NULL, -- in cents
    discount100 INTEGER             NULL,     -- in percent
    category    TEXT                NULL,

    CONSTRAINT c_stock CHECK ( stock >= 0 )
);

-- article images
CREATE TABLE IF NOT EXISTS Images
(
    id         INTEGER PRIMARY KEY NOT NULL,
    article_id INTEGER             NOT NULL,
    base64     TEXT                NOT NULL,
    FOREIGN KEY (article_id) REFERENCES Articles (id)
);

CREATE TABLE IF NOT EXISTS Reviews
(
    id         INTEGER PRIMARY KEY NOT NULL,
    article_id INTEGER             NOT NULL,
    rating     INTEGER             NOT NULL,
    content    TEXT                NULL,
    timestamp  INTEGER             NOT NULL,
    FOREIGN KEY (article_id) REFERENCES Articles (id),
    CONSTRAINT c_rating CHECK ( rating >= 0 AND rating <= 10)
);

CREATE TABLE IF NOT EXISTS Customers
(
    id      INTEGER PRIMARY KEY NOT NULL,
    name    TEXT                NOT NULL, --nachname
    surname TEXT                NOT NULL, --vorname,
    address TEXT                NOT NULL,
    country TEXT                NOT NULL,
    zip     TEXT                NOT NULL
);

CREATE TABLE IF NOT EXISTS Orders
(
    id          INTEGER PRIMARY KEY NOT NULL,
    customer_id INTEGER             NOT NULL,
    time        INTEGER             NOT NULL, --unix millis or epoch, TBD
    FOREIGN KEY (customer_id) REFERENCES Customers (id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE IF NOT EXISTS Accounts
(
    id          INTEGER PRIMARY KEY NOT NULL,
    customer_id INTEGER             NOT NULL,
    email       TEXT                NOT NULL,
    password    TEXT                NOT NULL,
    lang_i18n   TEXT                NOT NULL,
    FOREIGN KEY (customer_id) REFERENCES Customers (id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE IF NOT EXISTS OrderItems
(
    id         INTEGER NOT NULL PRIMARY KEY,
    order_id   INTEGER NOT NULL,
    article_id INTEGER NOT NULL,
    amount     INTEGER NOT NULL,
    -- art conf not needed

    CONSTRAINT cAmount CHECK (amount > 0),
    FOREIGN KEY (order_id) REFERENCES Orders (id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    FOREIGN KEY (article_id) REFERENCES Articles (id)
        ON DELETE SET NULL
        ON UPDATE CASCADE
);