create table t_deposit
(
    id      serial not null
        constraint t_deposit_pk
            primary key,
    caption varchar(255)
);

comment on table t_deposit is 'Месторождение';

alter table t_deposit
    owner to postgres;

create table t_cluster
(
    id         serial not null
        constraint t_cluster_pk
            primary key,
    caption    varchar(255),
    id_deposit integer
        constraint t_cluster_t_deposit_id_fk
            references t_deposit
);

comment on table t_cluster is 'Кусты';

alter table t_cluster
    owner to postgres;

create table t_customer
(
    id      serial not null
        constraint t_customer_pk
            primary key,
    caption varchar(255)
);

alter table t_customer
    owner to postgres;

create table t_well
(
    id          serial not null
        constraint t_well_pk
            primary key,
    caption     varchar(255),
    id_cluster  integer
        constraint t_well_t_cluster_id_fk
            references t_cluster,
    id_customer integer
        constraint t_well_t_customer_id_fk
            references t_customer
);

comment on table t_well is 'скважины';

alter table t_well
    owner to postgres;

create table t_telemetry
(
    id         serial not null
        constraint t_telemetry_pk
            primary key,
    remote_uid text,
    info       json,
    data       json,
    id_well    integer
        constraint t_telemetry_t_well_id_fk
            references t_well,
    version    varchar(64)
);

comment on table t_telemetry is 'таблица привязки телеметрии от комплектов к конкретной скважине.';

comment on column t_telemetry.remote_uid is 'Идентификатор передающего устройства. Может посторяться в списке, так как комплекты оборудования переезжают от скв. к скв.';

comment on column t_telemetry.info is 'Информация с панели о скважине';

comment on column t_telemetry.data is 'последние пришедшие данные со скважины в сыром виде';

comment on column t_telemetry.version is 'Версия ПО в комплекте';

alter table t_telemetry
    owner to postgres;

create index t_telemetry_remote_uid_index
    on t_telemetry (remote_uid);

create index t_telemetry_version_index
    on t_telemetry (version);

create table t_data_saub_base
(
    id                      serial  not null
        constraint t_data_saub_base_pk
            primary key,
    id_telemetry            integer not null
        constraint t_data_saub_base_t_telemetry_id_fk
            references t_telemetry,
    date                    timestamp with time zone,
    mode                    integer,
    well_depth              double precision,
    bit_depth               double precision,
    block_height            double precision,
    block_speed             double precision,
    block_speed_sp          double precision,
    pressure                double precision,
    pressure_idle           double precision,
    pressure_sp             double precision,
    pressure_delta_limit_max double precision,
    axial_load              double precision,
    axial_load_sp           double precision,
    axial_load_limit_max    double precision,
    hook_weight             double precision,
    hook_weight_idle        double precision,
    hook_weight_limit_min   double precision,
    hook_weight_limit_max   double precision,
    rotor_torque            double precision,
    rotor_torque_idle       double precision,
    rotor_torque_sp         double precision,
    rotor_torque_limit_max  double precision,
    rotor_speed             double precision,
    flow                    double precision,
    flow_idle               double precision,
    flow_delta_limit_max    double precision
);

comment on table t_data_saub_base is 'набор основных данных по SAUB';

comment on column t_data_saub_base.date is '''2021-10-19 18:23:54+05''';

comment on column t_data_saub_base.mode is 'Режим САУБ';

comment on column t_data_saub_base.well_depth is 'Глубина забоя';

comment on column t_data_saub_base.bit_depth is 'Положение инструмента';

comment on column t_data_saub_base.block_height is 'Высота талевого блока';

comment on column t_data_saub_base.block_speed is 'Скорость талевого блока';

comment on column t_data_saub_base.block_speed_sp is 'Скорости талевого блока. Задание';

comment on column t_data_saub_base.pressure is 'Давление';

comment on column t_data_saub_base.pressure_idle is 'Давление. Холостой ход';

comment on column t_data_saub_base.pressure_sp is 'Давление. Задание';

comment on column t_data_saub_base.pressure_delta_limit_max is 'Давление дифф. Аварийное макс.';

comment on column t_data_saub_base.axial_load is 'Осевая нагрузка';

comment on column t_data_saub_base.axial_load_sp is 'Осевая нагрузка. Задание';

comment on column t_data_saub_base.axial_load_limit_max is 'Осевая нагрузка. Аварийная макс.';

comment on column t_data_saub_base.hook_weight is 'Вес на крюке';

comment on column t_data_saub_base.hook_weight_idle is 'Вес на крюке. Холостой ход';

comment on column t_data_saub_base.hook_weight_limit_min is 'Вес на крюке. Посадка';

comment on column t_data_saub_base.hook_weight_limit_max is 'Вес на крюке. Затяжка';

comment on column t_data_saub_base.rotor_torque is 'Момент на роторе';

comment on column t_data_saub_base.rotor_torque_idle is 'Момент на роторе. Холостой ход';

comment on column t_data_saub_base.rotor_torque_sp is 'Момент на роторе. Задание';

comment on column t_data_saub_base.rotor_torque_limit_max is 'Момент на роторе. Аварийный макс.';

comment on column t_data_saub_base.rotor_speed is 'Обороты ротора';

comment on column t_data_saub_base.flow is 'Расход';

comment on column t_data_saub_base.flow_idle is 'Расход. Холостой ход';

comment on column t_data_saub_base.flow_delta_limit_max is 'Расход. Аварийный макс.';

alter table t_data_saub_base
    owner to postgres;

create table t_user
(
    id            serial not null
        constraint t_user_pk
            primary key,
    id_customer   integer
        constraint t_user_t_customer_id_fk
            references t_customer,
    login         varchar(255),
    password_hash varchar(255),
    state         smallint,
    level         integer,
    name          varchar(255),
    surname       varchar(255),
    patronymic    varchar(255)
);

comment on table t_user is 'Пользователи облака';

comment on column t_user.password_hash is 'соленый хэш пароля.
первые 5 символов - соль';

comment on column t_user.state is 'состояние:
100 - удален';

alter table t_user
    owner to postgres;

create table t_message
(
    id           serial                   not null
        constraint t_messages_pk
            primary key,
    id_telemetry integer
        constraint t_messages_t_telemetry_id_fk
            references t_telemetry,
    id_event     integer                  not null,
    id_user      integer,
    date         timestamp with time zone not null,
    state        integer,
    arg0         varchar(255),
    arg1         varchar(255),
    arg3         varchar(255),
    arg4         varchar(255)
);

alter table t_message
    owner to postgres;

create table t_event
(
    id_event         integer,
    version          varchar(64),
    id_category      integer,
    message_template text,
    constraint t_event_pk
        unique (id_event, version)
);

comment on table t_event is 'Справочник сообщений. Разделение по версиям посылок телеметрии.';

alter table t_event
    owner to postgres;

create table t_telemetry_user
(
    id_user      integer not null,
    id_telemetry integer not null
        constraint t_telemetry_user_t_telemetry_id_fk
            references t_telemetry,
    name         varchar(255),
    surname      varchar(255),
    patronymic   varchar(255),
    level        integer,
    constraint t_telemetry_user_pk
        unique (id_user, id_telemetry)
);

comment on table t_telemetry_user is 'Пользователи панели САУБ. Для сообщений.';

alter table t_telemetry_user
    owner to postgres;