CREATE TABLE bars (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL UNIQUE,
  pfand_cents INTEGER NOT NULL DEFAULT 0
);

CREATE TABLE drinks (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL UNIQUE,
  price_cents INTEGER NOT NULL,
  archived INTEGER NOT NULL DEFAULT 0
);

CREATE TABLE bar_drinks (
  bar_id INTEGER NOT NULL REFERENCES bars(id) ON DELETE CASCADE,
  drink_id INTEGER NOT NULL REFERENCES drinks(id) ON DELETE CASCADE,
  sort_order INTEGER NOT NULL DEFAULT 0,
  PRIMARY KEY (bar_id, drink_id)
);

CREATE TABLE transactions (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  bar_id INTEGER NOT NULL REFERENCES bars(id),
  created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
  total_cents INTEGER NOT NULL,
  crew INTEGER NOT NULL DEFAULT 0,
  client_ip TEXT,
  client_uuid TEXT NOT NULL UNIQUE
);

CREATE TABLE transaction_items (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  transaction_id INTEGER NOT NULL REFERENCES transactions(id) ON DELETE CASCADE,
  drink_id INTEGER NOT NULL REFERENCES drinks(id),
  qty INTEGER NOT NULL,
  unit_price_cents INTEGER NOT NULL,
  pfand_cents_per_unit INTEGER NOT NULL,
  is_return INTEGER NOT NULL DEFAULT 0
);

CREATE INDEX idx_tx_bar_created ON transactions(bar_id, created_at);
CREATE INDEX idx_txitem_tx ON transaction_items(transaction_id);
