CREATE TABLE IF NOT EXISTS users (
  id TEXT PRIMARY KEY,
  username TEXT NOT NULL UNIQUE,
  display_name TEXT NOT NULL,
  note TEXT NOT NULL DEFAULT '',
  password_hash TEXT NOT NULL,
  private_key_jwk TEXT NOT NULL,
  public_key_jwk TEXT NOT NULL,
  created_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS oauth_apps (
  id TEXT PRIMARY KEY,
  client_id TEXT NOT NULL UNIQUE,
  client_secret TEXT NOT NULL,
  name TEXT NOT NULL,
  redirect_uri TEXT NOT NULL,
  scopes TEXT NOT NULL,
  website TEXT,
  created_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS oauth_codes (
  code TEXT PRIMARY KEY,
  app_id TEXT NOT NULL,
  user_id TEXT NOT NULL,
  redirect_uri TEXT NOT NULL,
  scopes TEXT NOT NULL,
  expires_at INTEGER NOT NULL
);

CREATE TABLE IF NOT EXISTS statuses (
  id TEXT PRIMARY KEY,
  user_id TEXT NOT NULL,
  content TEXT NOT NULL,
  visibility TEXT NOT NULL DEFAULT 'public',
  in_reply_to_id TEXT,
  activity_id TEXT NOT NULL UNIQUE,
  object_id TEXT NOT NULL UNIQUE,
  created_at TEXT NOT NULL,
  url TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS media (
  id TEXT PRIMARY KEY,
  user_id TEXT NOT NULL,
  status_id TEXT,
  r2_key TEXT NOT NULL,
  mime_type TEXT NOT NULL,
  description TEXT,
  size INTEGER NOT NULL,
  created_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS follows (
  id TEXT PRIMARY KEY,
  follower_actor TEXT NOT NULL,
  local_user_id TEXT NOT NULL,
  inbox TEXT NOT NULL,
  accepted INTEGER NOT NULL DEFAULT 0,
  created_at TEXT NOT NULL,
  UNIQUE(follower_actor, local_user_id)
);

CREATE TABLE IF NOT EXISTS remote_activities (
  id TEXT PRIMARY KEY,
  actor TEXT NOT NULL,
  type TEXT NOT NULL,
  payload TEXT NOT NULL,
  received_at TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_statuses_created_at ON statuses(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_media_user ON media(user_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_follows_local_user ON follows(local_user_id);
