CREATE TABLE ropidvymi_metadata (LIKE ropidgtfs_metadata);
CREATE SEQUENCE ropidvymi_metadata_id_seq OWNED BY ropidvymi_metadata.id;
ALTER TABLE ropidvymi_metadata ALTER COLUMN id SET DEFAULT nextval('ropidvymi_metadata_id_seq');
ALTER TABLE ropidvymi_metadata ADD PRIMARY KEY (id);

ALTER TABLE ropidvymi_events_routes
    DROP CONSTRAINT ropidvymi_events_routes_fkey,
    DROP COLUMN id;

ALTER TABLE ropidvymi_events_stops
    DROP CONSTRAINT ropidvymi_events_stops_pkey,
    DROP CONSTRAINT ropidvymi_events_stops_fkey,
    DROP COLUMN id,
    ADD CONSTRAINT ropidvymi_events_stops_pkey PRIMARY KEY (event_id, vymi_id, node_number, stop_number);

ALTER TABLE ropidvymi_events
    DROP COLUMN id,
    ADD CONSTRAINT ropidvymi_events_pkey PRIMARY KEY (vymi_id);

DROP SEQUENCE ropidvymi_events_id_seq;
DROP SEQUENCE ropidvymi_events_routes_id_seq;
DROP SEQUENCE ropidvymi_events_stops_id_seq;

CREATE OR REPLACE FUNCTION ropidvymi_events_routes_gtfs_trigger_function()
RETURNS TRIGGER AS $$
BEGIN
    IF NEW.gtfs_route_id IS NULL THEN
        -- Find GTFS route id based on route short name
        -- B -> L992
        -- 231 -> L231
        SELECT route_id INTO NEW.gtfs_route_id FROM pid.ropidgtfs_routes WHERE route_short_name = NEW.name;
    END IF;
    RETURN NEW;
END
$$ LANGUAGE plpgsql;

CREATE TRIGGER gtfs_trigger BEFORE INSERT ON ropidvymi_events_routes
FOR EACH ROW EXECUTE PROCEDURE ropidvymi_events_routes_gtfs_trigger_function();

CREATE OR REPLACE FUNCTION ropidvymi_events_stops_gtfs_trigger_function()
RETURNS TRIGGER AS $$
DECLARE partialStopId VARCHAR;
BEGIN
    IF NEW.gtfs_stop_id IS NULL THEN
        -- Example: 145/3 -> U145Z3P
        partialStopId := 'U'|| NEW.node_number ||'Z'|| NEW.stop_number;
        SELECT stop_id INTO NEW.gtfs_stop_id FROM pid.ropidgtfs_stops WHERE stop_id ~ ('^'|| partialStopId ||'(P|N)?(_\\d+)?$');
    END IF;
    RETURN NEW;
END
$$ LANGUAGE plpgsql;

CREATE TRIGGER gtfs_trigger BEFORE INSERT ON ropidvymi_events_stops
FOR EACH ROW EXECUTE PROCEDURE ropidvymi_events_stops_gtfs_trigger_function();
