CREATE TYPE torrent_state AS ENUM (
    'pending',
    'downloading',
    'paused',
    'finished',
    'error',
    'stale'
);

CREATE TABLE torrents (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    info_hash TEXT NOT NULL UNIQUE,
    name TEXT,
    source TEXT NOT NULL,
    -- Set by the poller once librqbit resolves metadata and creates the
    -- output directory. NULL until then (magnet links take time to resolve).
    output_path TEXT,
    -- Per-torrent override of the download location. NULL = use the daemon
    -- default (<download_dir>/<torrent_name>/ for multi-file torrents).
    download_folder TEXT,
    -- Per-torrent override of the post-completion move target. NULL = use
    -- the daemon default (<download_dir>/completed/<torrent_name>/).
    move_after_completion_folder TEXT,
    total_bytes BIGINT,
    downloaded_bytes BIGINT NOT NULL DEFAULT 0,
    state torrent_state NOT NULL DEFAULT 'pending',
    error_message TEXT,
    added_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    completed_at TIMESTAMPTZ
);
