CREATE TABLE module_prefix_snapshot_row (
    tenant_id     UUID NOT NULL,
    module_id     UUID NOT NULL,
    ord           INTEGER NOT NULL,
    prefix        CIDR NOT NULL,
    community_id  UUID,
    source        TEXT NOT NULL DEFAULT '',
    PRIMARY KEY (tenant_id, module_id, ord),
    FOREIGN KEY (tenant_id, module_id)
        REFERENCES module_prefix_snapshot (tenant_id, module_id) ON DELETE CASCADE
);

INSERT INTO module_prefix_snapshot_row (tenant_id, module_id, ord, prefix, community_id, source)
SELECT mps.tenant_id,
    mps.module_id,
    (t.ordinality - 1)::int,
    (t.elem->>'prefix')::cidr,
    NULLIF(t.elem->>'community_id', '')::uuid,
    COALESCE(NULLIF(t.elem->>'source', ''), '')
FROM module_prefix_snapshot mps
CROSS JOIN LATERAL jsonb_array_elements(mps.prefixes_json) WITH ORDINALITY AS t(elem, ordinality)
WHERE jsonb_typeof(mps.prefixes_json) = 'array'
  AND jsonb_array_length(mps.prefixes_json) > 0;

ALTER TABLE module_prefix_snapshot DROP COLUMN prefixes_json;
