-- Add migration script here

CREATE TABLE IF NOT EXISTS User (
      id INTEGER PRIMARY KEY NOT NULL,
      email TEXT NOT NULL,
      name TEXT NOT NULL,
      role INTEGER NOT NULL,
      tz_offset INTEGER NOT NULL,
      FOREIGN KEY(role) REFERENCES UserRole(id)
);

CREATE TABLE IF NOT EXISTS UserRole (
    id INTEGER PRIMARY KEY NOT NULL,
    name TEXT NOT NULL UNIQUE
);

INSERT INTO UserRole (id, name) VALUES
    (1,'admin'),
    (10,'edit'),
    (99,'view');

CREATE TABLE IF NOT EXISTS InventoryItem (
     id INTEGER PRIMARY KEY NOT NULL,
     name TEXT NOT NULL,
     display_unit INTEGER NOT NULL DEFAULT 1,
     reorder_point REAL NOT NULL,
     allow_fractional_units BOOLEAN NOT NULL,
     FOREIGN KEY(display_unit) REFERENCES DisplayUnit(id)
);

CREATE TABLE IF NOT EXISTS Adjustment (
    id INTEGER PRIMARY KEY NOT NULL,
    item INTEGER NOT NULL,
    user INTEGER NOT NULL,
    create_date INTEGER NOT NULL,
    target_date INTEGER NOT NULL,
    amount REAL NOT NULL,
    reason INTEGER NOT NULL,
    unit_price INTEGER,
    FOREIGN KEY(user) REFERENCES User(id),
    FOREIGN KEY(item) REFERENCES InventoryItem(id),
    FOREIGN KEY(reason) REFERENCES AdjustmentReason(id)
);

CREATE TABLE IF NOT EXISTS AdjustmentReason (
    id INTEGER PRIMARY KEY NOT NULL,
    name TEXT NOT NULL
);

INSERT INTO AdjustmentReason (id, name) VALUES
    (0,'unknown'),
    (10,'sale'),
    (20,'destruction'),
    (25,'expiration'),
    (30,'theft'),
    (50,'new-stock');

CREATE TABLE IF NOT EXISTS DisplayUnit (
    id INTEGER PRIMARY KEY NOT NULL,
    unit TEXT NOT NULL,
    abbreviation TEXT NOT NULL
);

INSERT INTO DisplayUnit (id, unit, abbreviation) VALUES
    (1,'count', 'ct'),
    (2,'milliliter', 'ml'),
    (3,'milligram', 'mg');
