-- we don't need s3_segments multidimential array. we're moving it's functionality to a new table
ALTER TABLE IF EXISTS api.records
  DROP COLUMN s3_segments;



-- segments table
CREATE TABLE api.segments (
  id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  s3_key TEXT NOT NULL,
  s3_id TEXT NOT NULL,
  bytes bigint DEFAULT 0
);
GRANT all ON api.segments TO automation;
GRANT SELECT ON api.segments TO web_anon;


-- records-segments join table
CREATE TABLE api.records_segments(
  id INT GENERATED ALWAYS AS IDENTITY,
  record_id INT NOT NULL,
  segment_id INT NOT NULL,
  CONSTRAINT fk_record FOREIGN KEY(record_id) REFERENCES api.records(id),
  CONSTRAINT fk_segment FOREIGN KEY(segment_id) REFERENCES api.segments(id),
  PRIMARY KEY(id, record_id, segment_id)
);
GRANT all ON api.records_segments TO automation;
GRANT SELECT ON api.records_segments TO web_anon;
