CREATE SCHEMA traffic_light;

CREATE TABLE traffic_light.traffic_light (
    traffic_light_id bigserial PRIMARY KEY,
    position geometry(point, 3395) NOT NULL,
    position_variance double precision NOT NULL,
    heading double precision NOT NULL,
    heading_variance double precision NOT NULL,

    CONSTRAINT traffic_light_heading_check CHECK (heading >= 0.0 AND heading <= 360.0),
    CONSTRAINT traffic_light_heading_variance_check CHECK (heading_variance >= 0. AND heading_variance < 360.)
);

CREATE INDEX traffic_light_position_index ON traffic_light.traffic_light USING gist (position);

CREATE TABLE traffic_light.traffic_light_feature (
    traffic_light_id bigint REFERENCES traffic_light.traffic_light (traffic_light_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 (traffic_light_id, feature_id, min_x, min_y, max_x, max_y)
);

CREATE INDEX traffic_light_feature_traffic_light_id_index ON traffic_light.traffic_light_feature USING btree (traffic_light_id);
CREATE INDEX traffic_light_feature_feature_id_index ON traffic_light.traffic_light_feature USING btree (feature_id);

CREATE TABLE traffic_light.traffic_light_panorama (
    traffic_light_id bigint REFERENCES traffic_light.traffic_light (traffic_light_id) ON DELETE CASCADE,
    panorama_id bigint REFERENCES signals.panorama (panorama_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 (traffic_light_id, panorama_id, min_x, min_y, max_x, max_y)
);

CREATE INDEX traffic_light_panorama_traffic_light_id_index ON traffic_light.traffic_light_panorama USING btree (traffic_light_id);
CREATE INDEX traffic_light_panorama_panorama_id_index ON traffic_light.traffic_light_panorama USING btree (panorama_id);

CREATE TABLE traffic_light.hypotheses (
    hypothesis_id bigserial PRIMARY KEY,
    position geometry(Point, 3395) NOT NULL,
    object_id bigint NOT NULL,
    commit_id bigint NOT NULL,
    traffic_light_id bigint REFERENCES traffic_light.traffic_light (traffic_light_id) ON DELETE CASCADE,
    context jsonb NOT NULL,
    feedback_task_id bigint DEFAULT NULL
);

CREATE INDEX ON traffic_light.hypotheses USING btree(object_id, commit_id);
CREATE INDEX ON traffic_light.hypotheses USING btree(traffic_light_id);
CREATE INDEX ON traffic_light.hypotheses USING gist(position);
