CREATE TABLE IF NOT EXISTS magazines ( id uuid PRIMARY KEY, slug text UNIQUE NOT NULL, draft jsonb NOT NULL, revision integer NOT NULL DEFAULT 1, current_release uuid, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), deleted_at timestamptz, views bigint NOT NULL DEFAULT 0, downloads bigint NOT NULL DEFAULT 0 ); CREATE TABLE IF NOT EXISTS versions ( magazine_id uuid NOT NULL REFERENCES magazines(id), revision integer NOT NULL, draft jsonb NOT NULL, reason text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (magazine_id, revision) ); CREATE TABLE IF NOT EXISTS releases ( id uuid PRIMARY KEY, magazine_id uuid NOT NULL REFERENCES magazines(id), revision integer NOT NULL, draft jsonb NOT NULL, publish_at timestamptz NOT NULL, state text NOT NULL DEFAULT 'queued' CHECK (state IN ('queued','ready','failed','cancelled')), pages jsonb, media_ids uuid[] NOT NULL DEFAULT '{}', bytes bigint NOT NULL DEFAULT 0, error text, created_at timestamptz NOT NULL DEFAULT now(), published_at timestamptz ); CREATE INDEX IF NOT EXISTS releases_due ON releases (publish_at) WHERE state = 'queued'; CREATE INDEX IF NOT EXISTS releases_magazine ON releases (magazine_id, created_at DESC); CREATE TABLE IF NOT EXISTS media ( id uuid PRIMARY KEY, name text NOT NULL, mime text NOT NULL, extension text NOT NULL, bytes bigint NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), deleted_at timestamptz ); CREATE TABLE IF NOT EXISTS galleries ( id uuid PRIMARY KEY, name text NOT NULL, media_ids uuid[] NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), deleted_at timestamptz ); CREATE TABLE IF NOT EXISTS removed_items ( id uuid PRIMARY KEY, magazine_id uuid NOT NULL REFERENCES magazines(id), page_id uuid, sort_index integer NOT NULL, item jsonb NOT NULL, deleted_at timestamptz NOT NULL DEFAULT now(), restored_at timestamptz ); CREATE TABLE IF NOT EXISTS activity ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, kind text NOT NULL, message text NOT NULL, created_at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE IF NOT EXISTS sessions ( digest text PRIMARY KEY, expires_at timestamptz NOT NULL ); CREATE TABLE IF NOT EXISTS settings ( key text PRIMARY KEY );