CREATE TABLE IF NOT EXISTS teams (
    id SERIAL PRIMARY KEY,
    team_name character(16) NOT NULL,
    team_board_id INT NOT NULL,
    has_own_project BOOLEAN NOT NULL DEFAULT FALSE,
    sprint_alias TEXT
);

CREATE TYPE role AS ENUM ('analytic', 'backend', 'designer', 'frontend', 'qa', 'project');

CREATE TABLE IF NOT EXISTS employees (
    id SERIAL PRIMARY KEY,
    employee_name TEXT,
    employee_login TEXT UNIQUE,
    employee_role role -- analytic|backend|designer|frontend|qa
);

CREATE TABLE IF NOT EXISTS team_members (
    id SERIAL PRIMARY KEY,
    team_id int not null REFERENCES teams(id) ON DELETE CASCADE,
    employee_id int not null REFERENCES employees(id) ON DELETE CASCADE,
    start_datetime TIMESTAMPTZ NOT NULL,
    end_datetime TIMESTAMPTZ DEFAULT NULL
);

CREATE TABLE IF NOT EXISTS sprints (
    id SERIAL PRIMARY KEY,
    jira_sprint_id INT NOT NULL,
    team_id int not null REFERENCES teams(id) ON DELETE CASCADE,
    sprint_name TEXT NOT NULL,
    sprint_activate_datetime TIMESTAMPTZ NOT NULL,
    sprint_complete_datetime TIMESTAMPTZ NOT NULL,
    sprint_completion_percentage real DEFAULT NULL
);

CREATE TABLE IF NOT EXISTS tasks (
    id SERIAL PRIMARY KEY,
    task_type TEXT NOT NULL, -- Тип таски: bug, backend...
    task_key TEXT NOT NULL, -- Номер задачи
    task_title TEXT NOT NULL, -- Заголовок задачи
    employee_id int REFERENCES employees(id) ON DELETE SET NULL, -- Исполнитель
    sprint_id int REFERENCES sprints(id) ON DELETE SET NULL, -- Спринт
    estimate_seconds INT NOT NULL DEFAULT 0, -- Время оценки в секундах
    total_time_seconds INT NOT NULL DEFAULT 0, -- Суммарное время потраченное на работу в секундах
    take_in_work_datetime TIMESTAMPTZ, -- Дата-время взятия в работу
    resolution_datetime TIMESTAMPTZ, -- Дата-время завершения задачи
    lead_time_days INT, -- System Lead Time в рабочих днях
    recast_percentage real, -- Переработка в %
    efficiency_percentage real, -- КПД в %
    review_count INT NOT NULL DEFAULT 0, -- Количество заходов на ревью
    test_count INT NOT NULL DEFAULT 0 -- Количество заходов на тест
);
