-- Drop Jam Track Tracks constraints:
ALTER TABLE jam_track_tracks
  DROP CONSTRAINT jam_track_tracks_jam_track_id_fkey;

-- Drop Jam Track Tracks constraints:
ALTER TABLE jam_track_rights 
  DROP CONSTRAINT jam_track_rights_user_id_fkey,
  DROP CONSTRAINT jam_track_rights_jam_track_id_fkey;

-- Change Jam Tracks ID type to BIGINT so it can work like the other downloadable items:
CREATE SEQUENCE jam_tracks_next_seq;
ALTER TABLE jam_tracks 
  ALTER COLUMN id DROP DEFAULT,
  ALTER COLUMN id TYPE BIGINT USING nextval('jam_tracks_next_seq'),
  ALTER COLUMN id SET DEFAULT nextval('jam_tracks_next_seq');

-- Change referencing ID type and re-add constraints:
ALTER TABLE jam_track_tracks
  ALTER COLUMN jam_track_id TYPE BIGINT USING 0,
  ALTER COLUMN jam_track_id SET NOT NULL,
  ADD CONSTRAINT jam_track_tracks_jam_track_id_fkey FOREIGN KEY(jam_track_id) REFERENCES jam_tracks(id) ON DELETE CASCADE;

-- Change referencing ID type and re-add constraints.  Also
-- add S3 URL for user-specific downloads:
ALTER TABLE jam_track_rights 
  ALTER COLUMN id DROP DEFAULT,
  ALTER COLUMN id TYPE BIGINT USING nextval('tracks_next_tracker_seq'),
  ALTER COLUMN id SET DEFAULT nextval('tracks_next_tracker_seq'),
  ADD COLUMN url VARCHAR(2048),
  ADD COLUMN md5 VARCHAR,
  ADD COLUMN length INTEGER NOT NULL DEFAULT 0,
  ADD COLUMN download_count INTEGER NOT NULL DEFAULT 0,
  ADD COLUMN signed BOOLEAN NOT NULL DEFAULT FALSE,
  ADD COLUMN downloaded_since_sign BOOLEAN NOT NULL DEFAULT FALSE,
  ADD COLUMN last_signed_at timestamp without time zone NULL,
  ADD COLUMN last_downloaded_at timestamp without time zone NULL,
  ADD COLUMN created_at timestamp without time zone NOT NULL,
  ADD COLUMN updated_at timestamp without time zone NOT NULL,
  ALTER COLUMN jam_track_id TYPE BIGINT USING 0,
  ALTER COLUMN jam_track_id SET NOT NULL,
  ADD CONSTRAINT jam_track_rights_user_id_fkey FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
  ADD CONSTRAINT jam_track_rights_jam_track_id_fkey FOREIGN KEY(jam_track_id) REFERENCES jam_tracks(id) ON DELETE CASCADE;

ALTER TABLE notifications ADD COLUMN jam_track_right_id BIGINT REFERENCES jam_track_rights(id);