create table if not exists dynamic_plan_run
(
    id uuid primary key,
    status varchar(32) not null,
    request_id uuid not null,
    satellite_ids text not null,
    calculation_start timestamp not null,
    calculation_end timestamp not null,
    created_at timestamp not null,
    started_at timestamp,
    finished_at timestamp,
    duration_ms bigint,
    result_status varchar(64),
    routes_count integer,
    result_json text,
    error_message text
);

create index if not exists idx_dynamic_plan_run_status on dynamic_plan_run(status);
create index if not exists idx_dynamic_plan_run_request_id on dynamic_plan_run(request_id);

create table if not exists dynamic_plan_route
(
    id bigserial primary key,
    run_id uuid not null references dynamic_plan_run(id) on delete cascade,
    request_id uuid not null,
    satellite_id bigint not null,
    start_time timestamp not null,
    end_time timestamp not null,
    duration double precision not null,
    revolution bigint not null,
    roll double precision not null,
    contour_wkt text not null,
    route_order integer not null
);

create index if not exists idx_dynamic_plan_route_run_id on dynamic_plan_route(run_id);
create index if not exists idx_dynamic_plan_route_request_id on dynamic_plan_route(request_id);
create index if not exists idx_dynamic_plan_route_satellite_id on dynamic_plan_route(satellite_id);
create index if not exists idx_dynamic_plan_route_start_time on dynamic_plan_route(start_time);
create index if not exists idx_dynamic_plan_route_run_start on dynamic_plan_route(run_id, start_time);
