CREATE TABLE jam_track_licensors (
  id VARCHAR(64) PRIMARY KEY DEFAULT uuid_generate_v4() NOT NULL,
  name VARCHAR NOT NULL UNIQUE,
  description TEXT,
  attention TEXT,
  address_line_1 VARCHAR,
  address_line_2 VARCHAR,
  city VARCHAR,
  state VARCHAR,
  zip_code VARCHAR,
  contact VARCHAR,
  email VARCHAR,
  phone VARCHAR,
  created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW() NOT NULL,
  updated_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW() NOT NULL
);

CREATE TABLE jam_tracks (
  id VARCHAR(64) PRIMARY KEY DEFAULT uuid_generate_v4() NOT NULL,
  name VARCHAR NOT NULL UNIQUE,
  description TEXT,
  bpm decimal,
  time_signature VARCHAR,
  status VARCHAR,
  recording_type VARCHAR,
  original_artist TEXT,
  songwriter TEXT,
  publisher TEXT,
  pro VARCHAR,
  sales_region VARCHAR,
  price decimal,
  reproduction_royalty BOOLEAN,
  public_performance_royalty BOOLEAN,
  reproduction_royalty_amount DECIMAL,
  licensor_royalty_amount DECIMAL,
  pro_royalty_amount DECIMAL,
  url VARCHAR,
  md5 VARCHAR,
  length BIGINT,
  licensor_id VARCHAR(64) REFERENCES jam_track_licensors (id) ON DELETE SET NULL,
  genre_id VARCHAR(64) REFERENCES genres (id) ON DELETE SET NULL,
  created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW() NOT NULL,
  updated_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW() NOT NULL
);

CREATE TABLE jam_track_tracks (
  id VARCHAR(64) PRIMARY KEY DEFAULT uuid_generate_v4() NOT NULL,
  position INTEGER,
  track_type VARCHAR,
  jam_track_id VARCHAR(64) REFERENCES jam_tracks(id) ON DELETE CASCADE,
  instrument_id VARCHAR(64) REFERENCES instruments(id) ON DELETE SET NULL,
  part VARCHAR,
  url VARCHAR,
  md5 VARCHAR,
  length BIGINT,
  created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW() NOT NULL,
  updated_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW() NOT NULL
);

CREATE INDEX jam_track_tracks_position_uniqkey ON jam_track_tracks (position, jam_track_id);

CREATE TABLE jam_track_rights (
  id VARCHAR(64) PRIMARY KEY DEFAULT uuid_generate_v4() NOT NULL,
  user_id VARCHAR(64) NOT NULL REFERENCES users(id),
  jam_track_id VARCHAR(64) NOT NULL REFERENCES jam_tracks(id)
);

CREATE INDEX jam_tracks_rights_uniqkey ON jam_track_rights (user_id, jam_track_id);