CREATE TABLE IF NOT EXISTS issues (
    id BIGSERIAL PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    description TEXT,
    start_time TIMESTAMPTZ NOT NULL,
    end_time TIMESTAMPTZ NOT NULL,
    rsa_n BYTEA,
    rsa_e INT,
    rsa_private_pem BYTEA,
    created TIMESTAMPTZ NOT NULL DEFAULT now(),
    version INT NOT NULL DEFAULT 1
);

CREATE TABLE IF NOT EXISTS options (
    id BIGSERIAL PRIMARY KEY,
    issue_id BIGINT NOT NULL REFERENCES issues(id) ON DELETE CASCADE,
    label VARCHAR(255) NOT NULL,
    created TIMESTAMPTZ NOT NULL DEFAULT now(),
    version INT NOT NULL DEFAULT 1
);

CREATE TABLE IF NOT EXISTS blind_signs (
    user_id  BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    issue_id BIGINT NOT NULL REFERENCES issues(id) ON DELETE CASCADE,
    created  TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (user_id, issue_id)
);

CREATE TABLE IF NOT EXISTS votes (
    id        BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    option_id BIGINT NOT NULL REFERENCES options(id) ON DELETE CASCADE,
    nonce     BYTEA  NOT NULL,
    signature BYTEA  NOT NULL UNIQUE,
    created   TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX idx_votes_option_id ON votes(option_id);
CREATE INDEX idx_options_issue_id ON options(issue_id);
