CREATE TABLE IF NOT EXISTS shops (
  id TEXT PRIMARY KEY,
  name TEXT NOT NULL,
  location TEXT
);

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

CREATE TABLE IF NOT EXISTS bins (
  id TEXT PRIMARY KEY,
  name TEXT NOT NULL,
  location TEXT,
  capacity INTEGER NOT NULL DEFAULT 10
);

CREATE TABLE IF NOT EXISTS strains (
  id TEXT PRIMARY KEY,
  name TEXT NOT NULL,
  brand_id TEXT REFERENCES brands(id),
  type TEXT NOT NULL,
  default_thc REAL,
  default_cbd REAL,
  default_total_cannabinoids REAL,
  notes TEXT,
  created_at TEXT NOT NULL,
  UNIQUE(name, brand_id, type)
);

CREATE INDEX IF NOT EXISTS idx_strains_brand_type ON strains(brand_id, type);

CREATE TABLE IF NOT EXISTS products (
  id TEXT PRIMARY KEY,
  sku TEXT NOT NULL,
  asset_tag TEXT,
  name TEXT NOT NULL,
  brand_id TEXT REFERENCES brands(id),
  shop_id TEXT REFERENCES shops(id),
  bin_id TEXT REFERENCES bins(id),
  type TEXT NOT NULL,
  kind TEXT NOT NULL,
  weight REAL DEFAULT 0,
  last_audit_weight REAL,
  count_original INTEGER DEFAULT 0,
  count_last_audit INTEGER,
  unit_weight REAL DEFAULT 0,
  price REAL NOT NULL,
  thc REAL DEFAULT 0,
  cbd REAL DEFAULT 0,
  total_cannabinoids REAL DEFAULT 0,
  purchase_date TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'active',
  consumed_date TEXT,
  gone_date TEXT,
  rating INTEGER,
  notes TEXT
);

CREATE TABLE IF NOT EXISTS audits (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  product_id TEXT NOT NULL REFERENCES products(id) ON DELETE CASCADE,
  date TEXT NOT NULL,
  mode TEXT NOT NULL,
  value REAL NOT NULL,
  prev_value REAL,
  confirmed_by TEXT
);

CREATE INDEX IF NOT EXISTS idx_products_status ON products(status);
CREATE INDEX IF NOT EXISTS idx_audits_product ON audits(product_id, date);
