-- rForum schema — Discourse cloud provisioning
-- Inside rSpace shared DB, schema: rforum

CREATE TABLE IF NOT EXISTS rforum.users (
  id              UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  did             TEXT UNIQUE,
  username        TEXT,
  email           TEXT,
  created_at      TIMESTAMPTZ DEFAULT NOW(),
  updated_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS rforum.instances (
  id              UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id         UUID REFERENCES rforum.users(id),
  name            TEXT NOT NULL,
  domain          TEXT UNIQUE NOT NULL,
  status          TEXT NOT NULL DEFAULT 'pending'
                  CHECK (status IN ('pending','provisioning','installing','configuring','active','error','destroying','destroyed')),
  error_message   TEXT,
  discourse_version TEXT DEFAULT 'stable',
  provider        TEXT DEFAULT 'hetzner' CHECK (provider IN ('hetzner','digitalocean')),
  vps_id          TEXT,
  vps_ip          TEXT,
  region          TEXT DEFAULT 'nbg1',
  size            TEXT DEFAULT 'cx22',
  admin_email     TEXT,
  smtp_config     JSONB DEFAULT '{}',
  dns_record_id   TEXT,
  ssl_provisioned BOOLEAN DEFAULT FALSE,
  created_at      TIMESTAMPTZ DEFAULT NOW(),
  updated_at      TIMESTAMPTZ DEFAULT NOW(),
  provisioned_at  TIMESTAMPTZ,
  destroyed_at    TIMESTAMPTZ
);

CREATE INDEX IF NOT EXISTS idx_instances_user ON rforum.instances (user_id);
CREATE INDEX IF NOT EXISTS idx_instances_status ON rforum.instances (status);
CREATE INDEX IF NOT EXISTS idx_instances_domain ON rforum.instances (domain);

CREATE TABLE IF NOT EXISTS rforum.provision_logs (
  id              UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  instance_id     UUID NOT NULL REFERENCES rforum.instances(id) ON DELETE CASCADE,
  step            TEXT NOT NULL,
  status          TEXT NOT NULL DEFAULT 'running'
                  CHECK (status IN ('running','success','error','skipped')),
  message         TEXT,
  metadata        JSONB DEFAULT '{}',
  started_at      TIMESTAMPTZ DEFAULT NOW(),
  completed_at    TIMESTAMPTZ,
  created_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_logs_instance ON rforum.provision_logs (instance_id);
CREATE INDEX IF NOT EXISTS idx_logs_step ON rforum.provision_logs (step);
