// =============================================================================
// HeadlineSift.com — Fetch Logs Admin Page
// =============================================================================
// Server component — queries FetchLog with source include, filters by source,
// status, and date range, paginates results.

import type { Metadata } from "next";
import { prisma } from "@/lib/db/client";
import { FetchLogsPageClient } from "./FetchLogsPageClient";
import type { FetchLogRow } from "./FetchLogTable";

export const metadata: Metadata = { title: "Fetch Logs" };

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

interface FetchLogsPageProps {
  searchParams: Promise<{
    source?: string;
    status?: string;
    startDate?: string;
    endDate?: string;
    page?: string;
  }>;
}

const PAGE_SIZE = 50;

const VALID_STATUSES = ["STARTED", "SUCCESS", "PARTIAL", "FAILED"];

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

export default async function FetchLogsPage({
  searchParams,
}: FetchLogsPageProps) {
  const params = await searchParams;
  const sourceFilter = params.source ?? null;
  const statusFilter = params.status ?? null;
  const startDateFilter = params.startDate ?? null;
  const endDateFilter = params.endDate ?? null;
  const page = Math.max(1, parseInt(params.page ?? "1", 10) || 1);

  // ---- Build where clause ----
  const where: Record<string, unknown> = {};

  if (sourceFilter) {
    where.sourceId = sourceFilter;
  }

  if (statusFilter && VALID_STATUSES.includes(statusFilter)) {
    where.status = statusFilter;
  }

  if (startDateFilter || endDateFilter) {
    const startedAt: Record<string, Date> = {};
    if (startDateFilter) {
      startedAt.gte = new Date(startDateFilter);
    }
    if (endDateFilter) {
      // End of the selected day
      const end = new Date(endDateFilter);
      end.setHours(23, 59, 59, 999);
      startedAt.lte = end;
    }
    where.startedAt = startedAt;
  }

  // ---- Query fetch logs ----
  const totalCount = await prisma.fetchLog.count({ where: where as any });

  const logs = await prisma.fetchLog.findMany({
    where: where as any,
    orderBy: { startedAt: "desc" },
    skip: (page - 1) * PAGE_SIZE,
    take: PAGE_SIZE,
    include: {
      source: { select: { id: true, name: true } },
    },
  });

  const logRows: FetchLogRow[] = logs.map((l) => ({
    id: l.id,
    sourceId: l.sourceId,
    sourceName: l.source.name,
    startedAt: l.startedAt,
    endedAt: l.endedAt,
    status: l.status,
    articlesFound: l.articlesFound,
    articlesSaved: l.articlesSaved,
    duplicatesFound: l.duplicatesFound,
    errorMessage: l.errorMessage,
    createdAt: l.createdAt,
  }));

  // ---- Fetch sources for filter dropdown ----
  const sources = await prisma.source.findMany({
    select: { id: true, name: true },
    orderBy: { name: "asc" },
  });

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

  return (
    <FetchLogsPageClient
      logs={logRows}
      sourceFilter={sourceFilter}
      statusFilter={statusFilter}
      startDateFilter={startDateFilter}
      endDateFilter={endDateFilter}
      page={page}
      totalPages={totalPages}
      totalCount={totalCount}
      sourceOptions={sources.map((s) => ({ id: s.id, name: s.name }))}
    />
  );
}
