-- cowl-licensing D1 schema
-- Run: wrangler d1 execute cowl-licensing --file=schema.sql

CREATE TABLE IF NOT EXISTS products (
  bmt_id INTEGER NOT NULL,
  product TEXT NOT NULL,
  product_name TEXT NOT NULL,
  display_name TEXT NOT NULL,
  short_name TEXT NOT NULL,
  edition INTEGER NOT NULL,
  version TEXT NOT NULL,
  limit_version INTEGER NOT NULL,
  limit_activation INTEGER NOT NULL,
  limit_subscription INTEGER NOT NULL,
  limit_support INTEGER NOT NULL,
  download_url TEXT NOT NULL,
  PRIMARY KEY (bmt_id, product)
);

CREATE TABLE IF NOT EXISTS editions (
  product TEXT NOT NULL,
  edition INTEGER NOT NULL,
  name TEXT NOT NULL,
  PRIMARY KEY (product, edition)
);

CREATE TABLE IF NOT EXISTS serial_numbers (
  serial_number TEXT NOT NULL PRIMARY KEY,
  product TEXT NOT NULL,
  edition INTEGER NOT NULL,
  limit_version INTEGER NOT NULL,
  limit_activation INTEGER NOT NULL,
  limit_subscription INTEGER NOT NULL,
  limit_support INTEGER NOT NULL,
  note TEXT
);

CREATE TABLE IF NOT EXISTS licenses (
  registration_key TEXT NOT NULL,
  serial_number TEXT NOT NULL,
  product TEXT NOT NULL,
  edition INTEGER,
  version INTEGER,
  timestamp INTEGER NOT NULL,
  name TEXT NOT NULL,
  email TEXT NOT NULL,
  notify INTEGER NOT NULL,
  expiration_subscription INTEGER NOT NULL,
  expiration_support INTEGER NOT NULL,
  PRIMARY KEY (registration_key, serial_number, product)
);

CREATE INDEX IF NOT EXISTS idx_licenses_serial ON licenses(serial_number);
CREATE INDEX IF NOT EXISTS idx_licenses_product ON licenses(product);
CREATE INDEX IF NOT EXISTS idx_serial_numbers_product ON serial_numbers(product);
