// src/lib/keywords/serp-actions.ts — import/read competitor SERP snapshots on a keyword.
"use server";
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import {
  AnalyticsJobError,
  enqueueAnalyticsJob,
} from "@/lib/analytics/enqueue";
import { db } from "@/lib/db/client";
import { keywords } from "@/lib/db/domain-schema";
import { assertKeywordInActiveOrg } from "@/lib/sites/assert-site";
import type { SerpSnapshot } from "./serp-types";

export async function getSerpForKeywordAction(
  keywordId: string,
): Promise<Record<string, SerpSnapshot>> {
  await assertKeywordInActiveOrg(keywordId);
  const [row] = await db
    .select({ serp: keywords.serp })
    .from(keywords)
    .where(eq(keywords.id, keywordId));
  return row?.serp ?? {};
}

/**
 * Enqueue a `crawl-onpage` analytics job for this keyword's SERP competitors
 * (Firecrawl batch-scrape + WASM on-page parsing now run server-side in the
 * analytics service — see `services/analytics/src/crawl-onpage.ts`; this
 * action no longer fetches anything itself). `jobId: null` means the service
 * rejected the enqueue with 409 (a crawl is already `queued`/`running` for
 * this keyword) — treated as a soft success, not an error: the caller just
 * has nothing new to poll and tells the user so.
 */
export async function crawlSerpForKeywordAction(
  keywordId: string,
): Promise<{ ok: boolean; jobId?: string | null; error?: string }> {
  const siteId = await assertKeywordInActiveOrg(keywordId);

  let jobId: string | null;
  try {
    jobId = await enqueueAnalyticsJob({
      type: "crawl-onpage",
      siteId,
      payload: { keywordId },
    });
  } catch (err) {
    if (err instanceof AnalyticsJobError && err.status === 409) {
      jobId = null;
    } else {
      throw err;
    }
  }

  // Posés au moment de l'enqueue, avant que le job asynchrone n'ait écrit
  // quoi que ce soit — inoffensifs (le client les redéclenche de toute façon
  // en fin de poll via retry()/onDataChanged()/onImported()).
  revalidatePath("/content/planning");
  revalidatePath("/keywords/planning");
  revalidatePath(`/keywords/dispatch/${keywordId}`);
  return { ok: true, jobId };
}
