CREATE TABLE dumps (
    id TEXT PRIMARY KEY,
    kind TEXT NOT NULL,
    title TEXT NOT NULL,
    comment TEXT,
    user_id TEXT NOT NULL,
    created_at TEXT NOT NULL,
    url TEXT,
    rich_content TEXT,
    file_name TEXT,
    file_mime TEXT,
    file_size INTEGER,
    vote_count INTEGER NOT NULL DEFAULT 0,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

CREATE TABLE users (
  id TEXT PRIMARY KEY,
  username TEXT UNIQUE NOT NULL,
  password_hash TEXT NOT NULL,
  is_admin INTEGER NOT NULL DEFAULT 0,
  created_at TEXT NOT NULL,
  avatar_mime TEXT
);

CREATE TABLE votes (
  dump_id TEXT NOT NULL,
  user_id TEXT NOT NULL,
  created_at TEXT NOT NULL,
  PRIMARY KEY (dump_id, user_id),
  FOREIGN KEY (dump_id) REFERENCES dumps(id) ON DELETE CASCADE,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

-- v2: playlists
CREATE TABLE playlists (
  id          TEXT PRIMARY KEY,
  user_id     TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  title       TEXT NOT NULL,
  description TEXT,
  is_public   INTEGER NOT NULL DEFAULT 1,
  created_at  TEXT NOT NULL,
  image_mime  TEXT
);

CREATE TABLE playlist_dumps (
  playlist_id TEXT NOT NULL REFERENCES playlists(id) ON DELETE CASCADE,
  dump_id     TEXT NOT NULL REFERENCES dumps(id) ON DELETE CASCADE,
  position    INTEGER NOT NULL,
  added_at    TEXT NOT NULL,
  PRIMARY KEY (playlist_id, dump_id)
);

CREATE INDEX idx_dumps_user ON dumps(user_id);
CREATE INDEX idx_playlist_dumps_order ON playlist_dumps(playlist_id, position);
CREATE INDEX idx_playlists_user ON playlists(user_id);
