PRAGMA foreign_keys=ON;

CREATE TABLE
  users (
    user_id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT NOT NULL UNIQUE,
    display_name TEXT,
    email TEXT,
    status TEXT NOT NULL DEFAULT 'active', -- active | disabled
    created_at TEXT NOT NULL DEFAULT (datetime ('now'))
  );

CREATE TABLE
  api_keys (
    api_key_id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    api_key TEXT NOT NULL UNIQUE,
    api_secret TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'active', -- active | revoked
    last_used_at TEXT,
    created_at TEXT NOT NULL DEFAULT (datetime ('now')),
    FOREIGN KEY (user_id) REFERENCES users (user_id)
  );

CREATE TABLE
  access_channels (
    channel_id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    channel TEXT NOT NULL,
    identifier TEXT, -- chat_id, phone, webhook_id
    status TEXT NOT NULL DEFAULT 'active',
    created_at TEXT NOT NULL DEFAULT (datetime ('now')),
    FOREIGN KEY (user_id) REFERENCES users (user_id)
  );

INSERT INTO
  users (username, display_name, status)
VALUES
  ('system', 'System User', 'active');