CREATE TABLE media_files (
  id SERIAL PRIMARY KEY,
  name VARCHAR NOT NULL,
  artist_id INTEGER,
  album_id INTEGER,
  play_count INTEGER NOT NULL DEFAULT 0,
  comment VARCHAR DEFAULT ''
);

CREATE TABLE tags (
  id SERIAL PRIMARY KEY,
  name VARCHAR UNIQUE NOT NULL
);

CREATE TABLE playlists (
  id SERIAL PRIMARY KEY,
  name VARCHAR NOT NULL,
  media_file_ids INTEGER[] NOT NULL,
  mod_count INTEGER NOT NULL DEFAULT 0
);

CREATE TABLE bookmarks (
  id SERIAL PRIMARY KEY,
  name VARCHAR,
  playlist_id INTEGER NOT NULL,
  media_file_id INTEGER NOT NULL,
  play_index INTEGER NOT NULL,
  FOREIGN KEY (playlist_id) REFERENCES playlists(id),
  FOREIGN KEY (media_file_id) REFERENCES media_files(id)
);

CREATE TABLE media_files_tags (
  id SERIAL PRIMARY KEY,
  media_file_id INTEGER,
  tag_id INTEGER,
  FOREIGN KEY (media_file_id) REFERENCES media_files(id),
  FOREIGN KEY (tag_id) REFERENCES tags(id)
);

CREATE TABLE artists (
  id SERIAL PRIMARY KEY,
  name VARCHAR NOT NULL
);

CREATE TABLE albums (
  id SERIAL PRIMARY KEY,
  name VARCHAR NOT NULL,
  year INTEGER
);

CREATE TABLE images (
  id SERIAL PRIMARY KEY,
  url VARCHAR
);

CREATE TABLE artists_images (
  id SERIAL PRIMARY KEY,
  artist_id INTEGER,
  image_id INTEGER,
  FOREIGN KEY (artist_id) REFERENCES artists (id),
  FOREIGN KEY (image_id) REFERENCES images (id)
);

CREATE TABLE albums_images (
  id SERIAL PRIMARY KEY,
  album_id INTEGER,
  image_id INTEGER,
  FOREIGN KEY (album_id) REFERENCES albums (id),
  FOREIGN KEY (image_id) REFERENCES images (id)
);

CREATE TABLE artists_albums (
  artist_id INTEGER NOT NULL,
  album_id INTEGER NOT NULL,
  PRIMARY KEY (artist_id, album_id),
  FOREIGN KEY (artist_id) REFERENCES artists (id),
  FOREIGN KEY (album_id) REFERENCES albums (id)
);
