CREATE TABLE IF NOT EXISTS ordr_position (
	id SERIAL NOT NULL PRIMARY KEY,
	position_name TEXT NOT NULL
);

INSERT INTO ordr_position VALUES (0, 'Unassigned');

CREATE TABLE IF NOT EXISTS ordr_user (
    id SERIAL NOT NULL PRIMARY KEY,
    sub_id TEXT UNIQUE NOT NULL,
    user_name TEXT NOT NULL,
    job_position INTEGER NOT NULL DEFAULT 0 REFERENCES ordr_position ON DELETE SET NULL,
    active BOOLEAN NOT NULL DEFAULT TRUE,
    is_admin BOOLEAN NOT NULL DEFAULT FALSE
);

CREATE TABLE IF NOT EXISTS order_record (
    id SERIAL NOT NULL PRIMARY KEY,
    user_id INTEGER NOT NULL REFERENCES ordr_user(id),
    orderer TEXT NOT NULL,
    date_due TIMESTAMP NOT NULL,
    date_placed TIMESTAMP NOT NULL DEFAULT now(),
    amount_paid REAL NOT NULL DEFAULT 0,
    filled BOOLEAN NOT NULL DEFAULT FALSE,
    delivered BOOLEAN NOT NULL DEFAULT FALSE
);

CREATE TABLE IF NOT EXISTS item (
    id SERIAL NOT NULL PRIMARY KEY,
    item_name TEXT NOT NULL,
    in_season BOOLEAN NOT NULL DEFAULT TRUE
);

CREATE TABLE IF NOT EXISTS item_price_history (
    item_id INTEGER NOT NULL REFERENCES item(id) ON DELETE CASCADE,
    price REAL NOT NULL,
    valid_from TIMESTAMP NOT NULL DEFAULT now(),
    valid_to TIMESTAMP,
    PRIMARY KEY(item_id, price, valid_from)
);

CREATE TABLE IF NOT EXISTS order_item (
    item_id INTEGER NOT NULL REFERENCES item(id) ON DELETE CASCADE,
    order_id INTEGER NOT NULL REFERENCES order_record(id) ON DELETE CASCADE,
    quantity INTEGER NOT NULL,
    made INTEGER NOT NULL DEFAULT 0,
    created_at TIMESTAMP NOT NULL DEFAULT now(),
    PRIMARY KEY (item_id, order_id)
);

CREATE TABLE IF NOT EXISTS label (
    id SERIAL PRIMARY KEY,
    label_name TEXT NOT NULL,
    label_color INTEGER NOT NULL
);

CREATE TABLE IF NOT EXISTS order_label (
    order_id INTEGER NOT NULL REFERENCES order_record(id) ON DELETE CASCADE,
    label_id INTEGER NOT NULL REFERENCES label(id) ON DELETE CASCADE
);
