CREATE TABLE routes (
    id UUID PRIMARY KEY,
    name VARCHAR(200) NOT NULL,
    description TEXT,
    region_size_meters DOUBLE PRECISION NOT NULL,
    zoom_level INT NOT NULL,
    total_distance_meters DOUBLE PRECISION NOT NULL,
    total_points INT NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE route_points (
    id UUID PRIMARY KEY,
    route_id UUID NOT NULL REFERENCES routes(id) ON DELETE CASCADE,
    sequence_number INT NOT NULL,
    latitude DOUBLE PRECISION NOT NULL,
    longitude DOUBLE PRECISION NOT NULL,
    point_type VARCHAR(20) NOT NULL,
    segment_index INT NOT NULL,
    distance_from_previous DOUBLE PRECISION,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(route_id, sequence_number)
);

CREATE TABLE route_regions (
    route_id UUID NOT NULL REFERENCES routes(id) ON DELETE CASCADE,
    region_id UUID NOT NULL REFERENCES regions(id) ON DELETE CASCADE,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (route_id, region_id)
);

CREATE INDEX idx_route_points_route ON route_points(route_id, sequence_number);
CREATE INDEX idx_route_points_coords ON route_points(latitude, longitude);
CREATE INDEX idx_route_regions_route ON route_regions(route_id);
CREATE INDEX idx_route_regions_region ON route_regions(region_id);

