alter table inspection_plans
    add column if not exists trigger_type varchar(32);

update inspection_plans
set trigger_type = case
    when schedule_rule is null or btrim(schedule_rule) = '' then 'MANUAL'
    else 'PERIODIC'
end
where trigger_type is null;

alter table inspection_plans
    alter column trigger_type set default 'PERIODIC',
    alter column trigger_type set not null;

alter table inspection_plans
    add column if not exists schedule_config jsonb not null default '{}'::jsonb;

alter table inspection_plans
    add constraint chk_inspection_plans_trigger_type
    check (trigger_type in ('PERIODIC', 'MANUAL'));

create index if not exists idx_inspection_plans_trigger_status
    on inspection_plans(trigger_type, status, next_run_at);
