CREATE DATABASE vintagecoding;
USE vintagecoding;

CREATE TABLE roles (
  role_id INT PRIMARY KEY AUTO_INCREMENT,
  role VARCHAR(16) NOT NULL
);

INSERT INTO roles (role)
  VALUES ('owner'), ('admin'), ('contributor'), ('reader');

CREATE TABLE tags (
  tag_id INT PRIMARY KEY AUTO_INCREMENT,
  tag VARCHAR(16) NOT NULL
);

INSERT INTO tags (tag)
  VALUES ('linux'), ('web-dev'), ('raspberry-pi'), ('self-hosting');

CREATE TABLE user (
  user_id INT PRIMARY KEY,
  username VARCHAR(32) NOT NULL UNIQUE,
  email VARCHAR(64) NOT NULL UNIQUE,
  password_hash VARCHAR(256) NOT NULL,
  last_active TIMESTAMP DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  role_id INT NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  is_active BOOLEAN DEFAULT FALSE,
  profile_picture VARCHAR(256),
  FOREIGN KEY (role_id) REFERENCES roles (role_id)
);

CREATE TABLE articles (
  article_id INT PRIMARY KEY AUTO_INCREMENT,
  author_id INT NOT NULL,
  markdown_file_path VARCHAR(256) NOT NULL UNIQUE,
  title VARCHAR(64) NOT NULL,
  slug VARCHAR(32),
  read_count INT DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  published_at TIMESTAMP DEFAULT NULL,
  published BOOLEAN DEFAULT FALSE,
  excerpt VARCHAR(256),
  FOREIGN KEY (author_id) REFERENCES user(user_id)
);

CREATE TABLE article_tags (
    article_id INT NOT NULL,
    tag_id INT NOT NULL,
    PRIMARY KEY (article_id, tag_id),
    FOREIGN KEY (article_id) REFERENCES articles(article_id),
    FOREIGN KEY (tag_id) REFERENCES tags(tag_id)
);
