CREATE SCHEMA ugc;

-- ugc.task
CREATE TYPE ugc.task_status AS ENUM (
    'new',
    'acquired',
    'submitted',
    'done',
    'cancelled'
);

CREATE TABLE ugc.task (
    task_id bigserial PRIMARY KEY,
    status ugc.task_status NOT NULL,
    hull geometry NOT NULL,
    duration interval NOT NULL,
    distance float NOT NULL -- measured in physical (real) meters
);
CREATE INDEX ON ugc.task USING btree(status);
CREATE INDEX ON ugc.task USING gist(hull);

-- ugc.target
CREATE TYPE ugc.direction AS ENUM (
    'forward',
    'backward',
    'bidirectional'
);

CREATE TYPE ugc.traffic AS ENUM (
    'right-hand',
    'left-hand'
);

CREATE TABLE ugc.target (
    target_id bigserial PRIMARY KEY,
    task_id bigint NOT NULL REFERENCES ugc.task(task_id),
    oneway boolean NOT NULL,
    traffic ugc.traffic NOT NULL,
    direction ugc.direction NOT NULL,
    geom geometry(LineString, 3395) NOT NULL
);
CREATE INDEX ON ugc.target USING btree(task_id);

-- ugc.task_name
CREATE TABLE ugc.task_name (
    task_id bigint NOT NULL REFERENCES ugc.task(task_id),
    lang text NOT NULL,
    value text NOT NULL,
    PRIMARY KEY(task_id, lang)
);

-- ugc.assignment
CREATE TYPE ugc.assignment_status AS ENUM (
    'active',
    'expired',
    'abandoned',
    'completed',
    'accepted',
    'rejected'
);

CREATE TABLE ugc.assignment (
    assignment_id bigserial PRIMARY KEY,
    task_id bigint NOT NULL REFERENCES ugc.task(task_id),
    status ugc.assignment_status NOT NULL,
    assigned_to text NOT NULL,
    acquired_at timestamp with time zone NOT NULL,
    expires_at timestamp with time zone NOT NULL,
    submitted_at timestamp with time zone,
    evaluated_at timestamp with time zone
);
CREATE INDEX ON ugc.assignment USING btree(task_id);
CREATE INDEX ON ugc.assignment USING btree(assigned_to);
CREATE INDEX ON ugc.assignment USING btree(status);
CREATE INDEX ON ugc.assignment USING btree(acquired_at);

-- ugc.assignment_photo
CREATE TABLE ugc.assignment_photo (
    id bigserial PRIMARY KEY,
    assignment_id bigint NOT NULL REFERENCES ugc.assignment(assignment_id),
    taken_at timestamp with time zone NOT NULL,
    mds_group_id text NOT NULL,
    mds_path text NOT NULL
);
CREATE INDEX ON ugc.assignment_photo USING btree(assignment_id);

-- ugc.assignment_track_point
CREATE TABLE ugc.assignment_track_point (
    id bigserial PRIMARY KEY,
    assignment_id bigint NOT NULL REFERENCES ugc.assignment(assignment_id),
    position geometry(Point, 3395) NOT NULL,
    taken_at timestamp with time zone NOT NULL,
    speed float,
    heading float,
    accuracy float
);
CREATE INDEX ON ugc.assignment_track_point USING btree(assignment_id);

