BEGIN TRANSACTION;

PRAGMA foreign_keys = ON;

DROP TABLE IF EXISTS config;
CREATE TABLE config (
	name TEXT UNIQUE,  -- variable name
	value ANY          -- variable value
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_config_name ON config (name);
INSERT INTO config (name, value) VALUES ('schema_version', '20230107');

DROP TABLE IF EXISTS users;
CREATE TABLE users (
	user_id INTEGER PRIMARY KEY,                 -- PK
	username TEXT UNIQUE COLLATE NOCASE,         -- can be username or email
	password_hash TEXT,                          -- output of password_hash()
	timezone TEXT DEFAULT 'America/Los_Angeles'  -- for date formatting
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_username ON users (username COLLATE NOCASE);

DROP TABLE IF EXISTS posts;
CREATE TABLE posts (
	body TEXT,                    -- main text of the post
	created INTEGER,              -- timestamp when the post was created
	author_id INTEGER NOT NULL,   -- user_id of author
	FOREIGN KEY (author_id) REFERENCES users (user_id)
);
CREATE INDEX IF NOT EXISTS idx_posts_created ON posts (created DESC);

DROP TABLE IF EXISTS sessions;
CREATE TABLE sessions (
	token TEXT UNIQUE NOT NULL,
	user_id INTEGER NOT NULL,
	created INTEGER,
	updated INTEGER,
	FOREIGN KEY (user_id) REFERENCES users (user_id)
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_sessions_token ON sessions (token);
CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions (user_id);

COMMIT;
