-- Project Bifrost — initial schema
-- SPEC §7.2

CREATE TABLE users (
  id              INTEGER PRIMARY KEY AUTOINCREMENT,
  email           TEXT    UNIQUE NOT NULL,
  password_hash   TEXT    NOT NULL,
  name            TEXT    NOT NULL,
  organisation    TEXT    NOT NULL,
  role            TEXT    NOT NULL CHECK(role IN ('pilot', 'cab', 'fenja')),
  bio             TEXT    NOT NULL DEFAULT '',
  created_at      TEXT    NOT NULL DEFAULT (datetime('now')),
  last_seen_at    TEXT,
  active          INTEGER NOT NULL DEFAULT 1
);

CREATE TABLE invites (
  id                  INTEGER PRIMARY KEY AUTOINCREMENT,
  token_hash          TEXT    UNIQUE NOT NULL,
  email               TEXT    NOT NULL,
  name                TEXT    NOT NULL,
  organisation        TEXT    NOT NULL,
  role                TEXT    NOT NULL CHECK(role IN ('pilot', 'cab', 'fenja')),
  expires_at          TEXT    NOT NULL,
  used_at             TEXT,
  created_at          TEXT    NOT NULL DEFAULT (datetime('now')),
  created_by_user_id  INTEGER REFERENCES users(id)
);

CREATE TABLE sessions (
  id          TEXT    PRIMARY KEY,
  user_id     INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  expires_at  TEXT    NOT NULL,
  created_at  TEXT    NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE contributions (
  id          INTEGER PRIMARY KEY AUTOINCREMENT,
  user_id     INTEGER NOT NULL REFERENCES users(id),
  type        TEXT    NOT NULL CHECK(type IN ('idea', 'inspiration', 'question')),
  body_md     TEXT    NOT NULL,
  created_at  TEXT    NOT NULL DEFAULT (datetime('now')),
  edited_at   TEXT,
  hidden_at   TEXT
);

CREATE TABLE reactions (
  id               INTEGER PRIMARY KEY AUTOINCREMENT,
  user_id          INTEGER NOT NULL REFERENCES users(id),
  contribution_id  INTEGER NOT NULL REFERENCES contributions(id) ON DELETE CASCADE,
  created_at       TEXT    NOT NULL DEFAULT (datetime('now')),
  UNIQUE(user_id, contribution_id)
);

CREATE TABLE replies (
  id               INTEGER PRIMARY KEY AUTOINCREMENT,
  contribution_id  INTEGER NOT NULL REFERENCES contributions(id) ON DELETE CASCADE,
  user_id          INTEGER NOT NULL REFERENCES users(id),
  body_md          TEXT    NOT NULL,
  created_at       TEXT    NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE attendance (
  id            INTEGER PRIMARY KEY AUTOINCREMENT,
  user_id       INTEGER NOT NULL REFERENCES users(id),
  meeting_slug  TEXT    NOT NULL,
  status        TEXT    NOT NULL CHECK(status IN ('yes', 'no')),
  updated_at    TEXT    NOT NULL DEFAULT (datetime('now')),
  UNIQUE(user_id, meeting_slug)
);

CREATE INDEX idx_sessions_user       ON sessions(user_id);
CREATE INDEX idx_contributions_type  ON contributions(type);
CREATE INDEX idx_reactions_contrib   ON reactions(contribution_id);
CREATE INDEX idx_replies_contrib     ON replies(contribution_id);
CREATE INDEX idx_attendance_meeting  ON attendance(meeting_slug);
