CREATE EXTENSION IF NOT EXISTS pgcrypto;

-- =====================================================
-- 1. Таблица users
-- =====================================================
CREATE TABLE IF NOT EXISTS users (
    id BIGSERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    role VARCHAR(20) NOT NULL DEFAULT 'STUDENT'
);

-- Админ по умолчанию
INSERT INTO users (username, password, role)
VALUES ('admin', crypt('admin', gen_salt('bf', 10)), 'ADMIN')
ON CONFLICT (username) DO NOTHING;

-- =====================================================
-- 2. Таблица education_forms
-- =====================================================
CREATE TABLE IF NOT EXISTS education_forms (
    id BIGSERIAL PRIMARY KEY,
    name VARCHAR(100) UNIQUE NOT NULL
);

INSERT INTO education_forms (name) 
VALUES ('Бакалавриат'), ('Магистратура'), ('Специалитет')
ON CONFLICT (name) DO NOTHING;

-- =====================================================
-- 3. Таблица student_groups
-- =====================================================
CREATE TABLE IF NOT EXISTS student_groups (
    id BIGSERIAL PRIMARY KEY,
    name VARCHAR(100) UNIQUE NOT NULL,
    education_form_id BIGINT NOT NULL REFERENCES education_forms(id)
);

-- =====================================================
-- 4. Таблица lessons (ЭТА ЧАСТЬ БЫЛА ИСПОРЧЕНА)
-- =====================================================
CREATE TABLE IF NOT EXISTS lessons (
    id BIGSERIAL PRIMARY KEY,
    teacher_id BIGINT NOT NULL,
    group_id BIGINT NOT NULL,
    discipline_id BIGINT NOT NULL,
    day VARCHAR(255) NOT NULL,
    week VARCHAR(255) NOT NULL,
    time VARCHAR(255) NOT NULL
);

-- Добавляем внешние ключи
ALTER TABLE lessons ADD CONSTRAINT fk_lessons_teacher 
    FOREIGN KEY (teacher_id) REFERENCES users(id);

ALTER TABLE lessons ADD CONSTRAINT fk_lessons_group 
    FOREIGN KEY (group_id) REFERENCES student_groups(id);