alter table public.crm_config
  add column if not exists assignment_mode text not null default 'none',
  add column if not exists assignment_pool jsonb not null default '[]'::jsonb,
  add column if not exists assignment_cursor integer not null default 0,
  add column if not exists assignment_config jsonb not null default '{}'::jsonb;

do $$
begin
  if not exists (
    select 1
    from pg_constraint
    where conname = 'crm_config_assignment_mode_check'
  ) then
    alter table public.crm_config
      add constraint crm_config_assignment_mode_check
      check (assignment_mode in ('none', 'direct', 'round_robin', 'referrer'));
  end if;
end $$;

alter table public.referral_leads
  add column if not exists assigned_to_user_id uuid references public.platform_users(id) on delete set null,
  add column if not exists assignment_mode text,
  add column if not exists assigned_at timestamptz,
  add column if not exists assigned_by uuid references public.platform_users(id) on delete set null;

create index if not exists idx_referral_leads_assignee
  on public.referral_leads(tenant_id, assigned_to_user_id, status, bound_at desc);

create index if not exists idx_crm_config_assignment_mode
  on public.crm_config(tenant_id, assignment_mode);
