// src/services/jobs.ts
import { query } from "../db.js";

/**
 * Enqueue an embedding job if (and only if) there is no active job
 * (status IN ('pending','processing')) for the same (shop, product).
 *
 * Returns:
 *  - true  => a new job row was inserted
 *  - false => an active job already exists (skipped)
 *
 * Notes:
 *  - If the most recent job is 'done' or 'failed', a new row WILL be inserted.
 *  - This works without relying on a unique constraint; it uses NOT EXISTS.
 */
export async function enqueueEmbedding(shop: string, productId: string): Promise<boolean> {
  const sql = `
    WITH ins AS (
      INSERT INTO embedding_jobs (shop_domain, product_id, status, attempts, next_run_at)
      SELECT $1, $2, 'pending', 0, NULL
      WHERE NOT EXISTS (
        SELECT 1
        FROM embedding_jobs
        WHERE shop_domain = $1
          AND product_id  = $2
          AND status IN ('pending', 'processing')
      )
      RETURNING id
    )
    SELECT COALESCE((SELECT id FROM ins), NULL) AS id
  `;

  const rows = await query<{ id: number | null }>(sql, [shop, String(productId)]);
  const inserted = rows[0]?.id != null;
  return inserted;
}


