do $$
begin
  if not exists (
    select 1
    from pg_enum
    where enumlabel = 'scheduled'
      and enumtypid = 'public.campaign_status'::regtype
  ) then
    alter type public.campaign_status add value 'scheduled';
  end if;
end
$$;

alter table public.campaigns
  add column if not exists scheduled_for timestamptz,
  add column if not exists recipient_contact_ids jsonb,
  add column if not exists is_reusable_template boolean not null default false,
  add column if not exists source_campaign_id uuid references public.campaigns(id) on delete set null;

create index if not exists campaigns_scheduled_for_idx
  on public.campaigns (scheduled_for)
  where scheduled_for is not null and is_reusable_template = false;

create index if not exists campaigns_reusable_idx
  on public.campaigns (organization_id, is_reusable_template, updated_at desc);
