alter table public.content_import_jobs
  add column if not exists execution_mode text not null default 'sync',
  add column if not exists queued_at timestamptz,
  add column if not exists locked_at timestamptz,
  add column if not exists locked_by text,
  add column if not exists attempt_count integer not null default 0,
  add column if not exists max_attempts integer not null default 3,
  add column if not exists next_attempt_at timestamptz,
  add column if not exists parser_metadata jsonb not null default '{}'::jsonb;

do $$
begin
  if not exists (select 1 from pg_constraint where conname = 'content_import_jobs_execution_mode_check') then
    alter table public.content_import_jobs
      add constraint content_import_jobs_execution_mode_check
      check (execution_mode in ('sync', 'async'));
  end if;

  if not exists (select 1 from pg_constraint where conname = 'content_import_jobs_attempts_check') then
    alter table public.content_import_jobs
      add constraint content_import_jobs_attempts_check
      check (attempt_count >= 0 and max_attempts > 0 and attempt_count <= max_attempts);
  end if;
end $$;

create index if not exists idx_content_import_jobs_async_queue
  on public.content_import_jobs(tenant_id, status, next_attempt_at, created_at)
  where execution_mode = 'async' and status = 'pending';
