-- P5-5305: add articles

DROP TABLE IF EXISTS article_article_categories;
DROP TABLE IF EXISTS article_categories;
DROP TABLE IF EXISTS article_content;
DROP TABLE IF EXISTS articles;

CREATE TABLE articles (
    id serial PRIMARY KEY NOT NULL,
    created TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
    published TIMESTAMP WITH TIME ZONE,
    deleted TIMESTAMP WITH TIME ZONE,
    name TEXT
);


CREATE TABLE article_content (
    id serial NOT NULL,
    article_id INTEGER NOT NULL,
    market_id INTEGER NOT NULL,
    title TEXT,
    preamble TEXT,
    body TEXT,
    body_saved TIMESTAMP WITH TIME ZONE,
    meta_title TEXT,
    meta_description TEXT,
    slug TEXT
);


ALTER TABLE article_content
    ADD CONSTRAINT article_id
    FOREIGN KEY (article_id)
    REFERENCES articles(id) MATCH SIMPLE;


ALTER TABLE article_content
    ADD CONSTRAINT market_id
    FOREIGN KEY (market_id)
    REFERENCES markets(id) MATCH SIMPLE;


CREATE TABLE article_categories (
    id serial PRIMARY KEY NOT NULL,
    name TEXT
);


INSERT INTO article_categories (name) VALUES
    ('News'),
    ('Pressroom'),
    ('Interiors'),
    ('Trends and inspiration'),
    ('Furniture'),
    ('Home improvement'),
    ('Home decor'),
    ('Lighting'),
    ('Wall art'),
    ('Style guides');


CREATE TABLE article_article_categories (
    article_id INTEGER NOT NULL,
    category_id INTEGER NOT NULL,
    main INTEGER DEFAULT 0,
    PRIMARY KEY (article_id, category_id)
);


ALTER TABLE article_article_categories
    ADD CONSTRAINT article_id
    FOREIGN KEY (article_id)
    REFERENCES articles(id) MATCH SIMPLE;


ALTER TABLE article_article_categories
    ADD CONSTRAINT category_id
    FOREIGN KEY (category_id)
    REFERENCES article_categories(id) MATCH SIMPLE;
