"use server";
// src/lib/analytics/actions.ts — read an ETL job's status (org-scoped).
import { and, eq } from "drizzle-orm";
import { getActiveOrgId } from "@/lib/active-org";
import { db } from "@/lib/db/client";
import { analyticsJobs, sites } from "@/lib/db/domain-schema";

type JobTotals = {
  read?: number;
  matched?: number;
  created?: number;
  upserted?: number;
};

export type AnalyticsJobStatus = {
  status: "queued" | "running" | "done" | "failed";
  totals: JobTotals;
  error: string | null;
};

/**
 * Fetch a job by id, scoped to the caller's active org via its site. Returns
 * null when the job is absent or belongs to another org. Polled by the dialog.
 */
export async function getAnalyticsJob(
  id: string,
): Promise<AnalyticsJobStatus | null> {
  const orgId = await getActiveOrgId();
  const [row] = await db
    .select({
      status: analyticsJobs.status,
      totals: analyticsJobs.totals,
      error: analyticsJobs.error,
    })
    .from(analyticsJobs)
    .innerJoin(sites, eq(analyticsJobs.siteId, sites.id))
    .where(and(eq(analyticsJobs.id, id), eq(sites.orgId, orgId)))
    .limit(1);
  return row ?? null;
}
