CREATE TABLE publications (
  id          SERIAL PRIMARY KEY,
  title       VARCHAR(255) NOT NULL,
  author      VARCHAR(255),
  osdb_pub_id VARCHAR(50)  NOT NULL UNIQUE,
  image_data  BYTEA,
  created_at  TIMESTAMPTZ  NOT NULL DEFAULT NOW(),
  updated_at  TIMESTAMPTZ  NOT NULL DEFAULT NOW()
);

CREATE TABLE publication_fruits (
  publication_id INTEGER NOT NULL REFERENCES publications(id) ON DELETE CASCADE,
  fruit_id       INTEGER NOT NULL REFERENCES fruits(id) ON DELETE CASCADE,
  PRIMARY KEY (publication_id, fruit_id)
);

CREATE TABLE publication_descriptions (
  id             SERIAL PRIMARY KEY,
  publication_id INTEGER NOT NULL REFERENCES publications(id) ON DELETE CASCADE,
  fruit_id       INTEGER NOT NULL REFERENCES fruits(id) ON DELETE CASCADE,
  pdf_data       BYTEA   NOT NULL,
  created_at     TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  UNIQUE (publication_id, fruit_id)
);

CREATE TABLE publication_fruit_images (
  id             SERIAL PRIMARY KEY,
  publication_id INTEGER      NOT NULL REFERENCES publications(id) ON DELETE CASCADE,
  fruit_id       INTEGER      NOT NULL REFERENCES fruits(id) ON DELETE CASCADE,
  filename       VARCHAR(255),
  data           BYTEA        NOT NULL,
  image_type     VARCHAR(20)  NOT NULL DEFAULT 'fruit',
  created_at     TIMESTAMPTZ  NOT NULL DEFAULT NOW()
);
