CREATE TABLE IF NOT EXISTS shares (
    id BIGSERIAL PRIMARY KEY,
    work_info_id BIGINT NOT NULL,
    client_id INT NOT NULL,
    enonce1 TEXT,
    nonce2 TEXT,
    nonce TEXT,
    ntime TEXT,
    diff DOUBLE PRECISION NOT NULL,
    sdiff DOUBLE PRECISION NOT NULL,
    hash TEXT,
    result BOOLEAN,
    errn INT,
    create_date TEXT NOT NULL,
    create_ts TIMESTAMPTZ NOT NULL,
    create_by TEXT,
    create_code TEXT,
    create_inet TEXT,
    worker_name TEXT,
    username TEXT,
    address TEXT,
    agent TEXT
);

CREATE INDEX IF NOT EXISTS shares_create_ts_desc ON shares (create_ts DESC);
CREATE INDEX IF NOT EXISTS shares_sdiff_desc ON shares (sdiff DESC);
CREATE INDEX IF NOT EXISTS shares_create_ts_sdiff ON shares (create_ts, sdiff DESC);

CREATE TABLE IF NOT EXISTS top_shares (
    id BIGSERIAL PRIMARY KEY,
    work_info_id BIGINT NOT NULL,
    client_id INT NOT NULL,
    enonce1 TEXT,
    nonce2 TEXT,
    nonce TEXT,
    ntime TEXT,
    diff DOUBLE PRECISION NOT NULL,
    sdiff DOUBLE PRECISION NOT NULL,
    hash TEXT,
    result BOOLEAN,
    errn INT,
    create_date TEXT NOT NULL,
    create_ts TIMESTAMPTZ NOT NULL,
    create_by TEXT,
    create_code TEXT,
    create_inet TEXT,
    worker_name TEXT,
    username TEXT,
    address TEXT,
    agent TEXT
);

CREATE INDEX IF NOT EXISTS top_shares_sdiff_desc ON top_shares (sdiff DESC);

CREATE TABLE IF NOT EXISTS time_window_high_shares (
    time_window_id TEXT PRIMARY KEY,
    time_window_name TEXT NOT NULL,
    sdiff DOUBLE PRECISION NOT NULL,
    time TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS daily_stats (
    date DATE PRIMARY KEY,
    share_count INT NOT NULL,
    top_share JSONB NOT NULL,
    pool_hashrate DOUBLE PRECISION NOT NULL,
    workers JSONB NOT NULL,
    expires_at TIMESTAMPTZ NULL
);
