CREATE DATABASE r_calendar ENCODING 'UTF-8';

\c r_calendar

CREATE TABLE IF NOT EXISTS c_user (
    id SERIAL PRIMARY KEY NOT NULL,
    name TEXT NOT NULL UNIQUE,
    email TEXT,
    password TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS calendar (
    id SERIAL PRIMARY KEY NOT NULL,
    name TEXT NOT NULL,
    url TEXT UNIQUE NOT NULL,
    is_public BOOLEAN DEFAULT TRUE
);

CREATE TABLE IF NOT EXISTS event (
    id SERIAL PRIMARY KEY NOT NULL,
    name TEXT NOT NULL,
    site TEXT,
    is_public BOOLEAN DEFAULT TRUE
);

CREATE TABLE IF NOT EXISTS edition (
    id SERIAL PRIMARY KEY NOT NULL,
    date_from INT NOT NULL CHECK (date_from > 0),
    date_to INT CHECK (date_to > date_from),
    name TEXT NOT NULL,
    location TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS event_in_calendar (
    calendar_id INT REFERENCES calendar(id) NOT NULL,
    event_id INT REFERENCES event(id),
    PRIMARY KEY (calendar_id, event_id)
);

CREATE TABLE IF NOT EXISTS user_in_calendar (
    calendar_id INT REFERENCES calendar(id) NOT NULL,
    user_id INT REFERENCES c_user(id) NOT NULL,
    can_write BOOLEAN DEFAULT FALSE,
    is_owner BOOLEAN DEFAULT FALSE,
    PRIMARY KEY (calendar_id, user_id)
);

CREATE TABLE IF NOT EXISTS user_in_event (
    event_id INT REFERENCES event(id) NOT NULL,
    user_id INT REFERENCES c_user(id) NOT NULL,
    can_write BOOLEAN DEFAULT FALSE,
    is_owner BOOLEAN DEFAULT FALSE,
    PRIMARY KEY (event_id, user_id)
);
