// =============================================================================
// HeadlineSift.com — Jobs Admin Page
// =============================================================================
// Server component — queries Prisma with status/type filters, renders the
// read-only job monitor with retry/cancel actions.

import type { Metadata } from "next";
import { prisma } from "@/lib/db/client";
import { JobsPageClient } from "./JobsPageClient";
import type { JobRow } from "./JobTable";

export const metadata: Metadata = { title: "Jobs" };

// ============================================================================
// Types
// ============================================================================

interface JobsPageProps {
  searchParams: Promise<{
    status?: string;
    type?: string;
    success?: string;
    error?: string;
    page?: string;
  }>;
}

const PAGE_SIZE = 50;

// Clean up success/error messages from searchParams
function successMessage(key: string): string | null {
  const messages: Record<string, string> = {
    retried: "Job reset to PENDING — the worker will retry it shortly.",
    cancelled: "Job cancelled successfully.",
  };
  return messages[key] ?? null;
}

// ============================================================================
// Page
// ============================================================================

export default async function JobsPage({ searchParams }: JobsPageProps) {
  const params = await searchParams;
  const statusFilter = params.status ?? null;
  const typeFilter = params.type ?? null;
  const successKey = params.success ?? null;
  const errorKey = params.error ?? null;
  const page = Math.max(1, parseInt(params.page ?? "1", 10) || 1);

  // ---- Resolve messages ----
  const successMsg = successKey ? successMessage(successKey) : null;
  const errorMsg = errorKey ? errorKey.replace(/\+/g, " ") : null;

  // ---- Build where clause ----
  const where: Record<string, string> = {};
  if (
    statusFilter &&
    ["PENDING", "RUNNING", "COMPLETED", "FAILED", "CANCELLED"].includes(
      statusFilter,
    )
  ) {
    where.status = statusFilter;
  }
  if (
    typeFilter &&
    [
      "FETCH_SOURCE",
      "FETCH_ALL_SOURCES",
      "CLUSTER_ARTICLES",
      "RANK_STORIES",
      "GENERATE_AI_ANALYSIS",
      "PUBLISH_APPROVED_STORIES",
      "BACKUP_DATABASE",
    ].includes(typeFilter)
  ) {
    where.type = typeFilter;
  }

  // ---- Query jobs ----
  const totalCount = await prisma.job.count({ where });

  const jobs = await prisma.job.findMany({
    where,
    orderBy: [{ createdAt: "desc" }],
    skip: (page - 1) * PAGE_SIZE,
    take: PAGE_SIZE,
    select: {
      id: true,
      type: true,
      status: true,
      payloadJson: true,
      attempts: true,
      maxAttempts: true,
      runAfter: true,
      lockedAt: true,
      lockedBy: true,
      startedAt: true,
      completedAt: true,
      errorMessage: true,
      createdAt: true,
      updatedAt: true,
    },
  });

  const jobRows: JobRow[] = jobs.map((j) => ({
    id: j.id,
    type: j.type,
    status: j.status,
    payloadJson: j.payloadJson,
    attempts: j.attempts,
    maxAttempts: j.maxAttempts,
    runAfter: j.runAfter,
    lockedAt: j.lockedAt,
    lockedBy: j.lockedBy,
    startedAt: j.startedAt,
    completedAt: j.completedAt,
    errorMessage: j.errorMessage,
    createdAt: j.createdAt,
    updatedAt: j.updatedAt,
  }));

  const totalPages = Math.ceil(totalCount / PAGE_SIZE);

  return (
    <JobsPageClient
      jobs={jobRows}
      statusFilter={statusFilter}
      typeFilter={typeFilter}
      page={page}
      totalPages={totalPages}
      totalCount={totalCount}
      successMsg={successMsg}
      errorMsg={errorMsg}
    />
  );
}
