CREATE TYPE eye.object_type AS ENUM (
    'sign',
    'traffic_light',
    'house_number',
    'road_marking'
);

CREATE TABLE eye.object (
    object_id bigserial PRIMARY KEY,
    primary_detection_id bigint NOT NULL REFERENCES eye.detection (detection_id) ON DELETE CASCADE,
    txn_id bigint NOT NULL,
    deleted boolean NOT NULL,
    exists boolean NOT NULL,
    type eye.object_type NOT NULL,
    attrs jsonb NOT NULL
);

CREATE UNIQUE INDEX eye_object_primary_detection_id_index ON eye.object USING btree(primary_detection_id);
CREATE INDEX eye_object_txn_id_index ON eye.object USING btree(txn_id);

CREATE TABLE eye.object_location(
    object_id bigint NOT NULL REFERENCES eye.object (object_id) ON DELETE CASCADE,
    txn_id bigserial NOT NULL,
    position geometry(point, 3395) NOT NULL,
    rotation real[4] NOT NULL -- from global axes to frame ones (quaternion)
);

CREATE UNIQUE INDEX eye_object_location_object_id_index ON eye.object_location USING btree(object_id);
CREATE INDEX eye_object_location_txn_id_index ON eye.object_location USING btree(txn_id);
CREATE INDEX eye_object_location_position_index ON eye.object_location USING gist(position);

CREATE TABLE eye.primary_detection_relation (
    relation_id bigserial PRIMARY KEY,
    primary_detection_id bigint NOT NULL REFERENCES eye.detection (detection_id) ON DELETE CASCADE,
    detection_id bigint NOT NULL REFERENCES eye.detection (detection_id) ON DELETE CASCADE,
    txn_id bigserial NOT NULL,
    deleted boolean NOT NULL
);

CREATE INDEX eye_primary_detection_relation_primary_detection_id_index ON eye.primary_detection_relation USING btree(primary_detection_id);
CREATE UNIQUE INDEX eye_primary_detection_relation_detection_id_index ON eye.primary_detection_relation USING btree(detection_id);
CREATE INDEX eye_primary_detection_relation_txn_id_index ON eye.primary_detection_relation USING btree(txn_id);
