-- create users table
CREATE TABLE pet_project.users
(
    user_id           UInt32,
    name              String,
    age               UInt16,
    email             String,
    registration_date DateTime
)
    ENGINE MergeTree()
        ORDER BY (user_id);

-- create table course
DROP TABLE IF EXISTS pet_project.courses;
CREATE TABLE pet_project.courses
(
    course_id  UInt32,
    title      String,
    category   String,
    created_at DateTime
)
    ENGINE ReplacingMergeTree(created_at)
        ORDER BY (course_id);

-- create table dim_lesson
DROP TABLE pet_project.lessons;
CREATE TABLE pet_project.lessons
(
    lesson_id    UInt32,
    title        String,
    duration_min UInt16,
    course_id    UInt32
)
    ENGINE MergeTree()
        ORDER BY (lesson_id, course_id);

-- create table fact_lesson_views
DROP TABLE pet_project.fact_lesson_views;
CREATE TABLE pet_project.fact_lesson_views
(
    id        UInt32,
    user_id   UInt32,
    lesson_id UInt32,
    course_id UInt32,
    viewed_at Datetime
)
    ENGINE MergeTree()
        PARTITION BY toYYYYMM(viewed_at)
        ORDER BY (course_id, lesson_id, user_id);
ALTER TABLE pet_project.fact_lesson_views
ADD PROJECTION user_lookup (
    SELECT * ORDER BY (user_id, lesson_id, course_id)
);

ALTER TABLE pet_project.fact_lesson_views
MATERIALIZE PROJECTION user_lookup;

-- create table enrollments
CREATE TABLE pet_project.enrollments
(
    id          UInt32,
    user_id     UInt32,
    course_id   UInt32,
    enrolled_at DateTime
)
    ENGINE MergeTree()
        ORDER BY (user_id, course_id);
