CREATE SCHEMA hypotheses;

CREATE TABLE hypotheses.sign (
    sign_id bigserial PRIMARY KEY,
    type text NOT NULL,
    position geometry(point, 3395) NOT NULL,
    position_variance double precision NOT NULL,
    heading double precision NOT NULL,
    heading_variance double precision NOT NULL,

    CONSTRAINT sign_heading_check CHECK (heading >= 0. AND heading < 360.),
    CONSTRAINT sign_heading_variance_check CHECK (heading_variance >= 0. AND heading_variance < 360.)
);

CREATE INDEX sign_position_index ON hypotheses.sign USING gist (position);
CREATE INDEX sign_type_index ON hypotheses.sign USING btree (type);

CREATE TABLE hypotheses.sign_feature (
    sign_id bigint REFERENCES hypotheses.sign (sign_id) ON DELETE CASCADE,
    feature_id bigint REFERENCES signals.feature (feature_id) ON DELETE CASCADE,

    min_x int NOT NULL,
    min_y int NOT NULL,
    max_x int NOT NULL,
    max_y int NOT NULL,

    UNIQUE (sign_id, feature_id, min_x, min_y, max_x, max_y),

    CONSTRAINT sign_feature_box_check CHECK (
        min_x >= 0 AND min_y >= 0 AND max_x >= 0 AND max_y >= 0
    )
);

CREATE INDEX sign_feature_sign_id_index ON hypotheses.sign_feature USING btree (sign_id);
CREATE INDEX sign_feature_feature_id_index ON hypotheses.sign_feature USING btree (feature_id);
