create sequence if not exists task_numbers_seq;

create table tasks
(
    id          bigint generated by default as identity primary key,
    number      bigint      not null unique,
    template_id bigint references templates (id) on update cascade on delete set null,
    template_name text       not null default '',
    type        smallint    not null check (type > 0),
    params      jsonb       not null default '{}'::jsonb,
    targets     jsonb       not null default '{}'::jsonb,
    status      smallint    not null check (status > 0),
    percent     real        not null,
    state       text,
    created_at  timestamptz not null default now(),
    updated_at  timestamptz not null default now(),
    deleted_at  timestamptz
);

create index tasks_template_id_idx on tasks (template_id);
create index tasks_status_idx on tasks (status);
create index tasks_type_idx on tasks (type);
create index tasks_template_name_trgm_idx on tasks using gin (template_name gin_trgm_ops);
