/*
*  author: Yagnik Poshiya
*  organization: Webbrains Technologies Private Limited
*/

import type { SupabaseClient } from '@supabase/supabase-js';

const ACTIVE_JOB_STATUSES = ['queued', 'processing'] as const;

/**
 * Whether the embedding worker currently has, or is about to have, this
 * document in hand. Editing during that window would race the worker.
 */
export async function hasActiveEmbeddingJobForDocument(
  supabase: SupabaseClient,
  documentId: string,
): Promise<{ ok: true; active: boolean } | { ok: false; message: string }> {
  const { data, error } = await supabase
    .from('document_processing_jobs')
    .select('id')
    .eq('document_id', documentId)
    .in('status', [...ACTIVE_JOB_STATUSES])
    .limit(1);

  if (error) return { ok: false, message: error.message };
  return { ok: true, active: (data ?? []).length > 0 };
}
