// =============================================================================
// HeadlineSift.com — Source Mappings Admin Page
// =============================================================================
// Server component — queries Prisma with include relations, reads searchParams,
// fetches dropdown options, renders the CRUD UI.

import type { Metadata } from "next";
import { prisma } from "@/lib/db/client";
import { SourceMappingsPageClient } from "./SourceMappingsPageClient";
import type { SourceMappingRow } from "./SourceMappingTable";

export const metadata: Metadata = { title: "Source Mappings" };

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

interface SourceMappingsPageProps {
  searchParams: Promise<{
    edit?: string;
    success?: string;
    error?: string;
    source?: string;
    country?: string;
    category?: string;
  }>;
}

// Clean up success/error messages from searchParams
function successMessage(key: string): string | null {
  const messages: Record<string, string> = {
    created: "Source mapping created successfully.",
    updated: "Source mapping updated successfully.",
    deleted: "Source mapping deleted successfully.",
    activated: "Source mapping activated — the fetcher will use it.",
    deactivated: "Source mapping deactivated — it will be skipped by the fetcher.",
  };
  return messages[key] ?? null;
}

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

export default async function SourceMappingsPage({
  searchParams,
}: SourceMappingsPageProps) {
  const params = await searchParams;
  const editId = params.edit ?? null;
  const successKey = params.success ?? null;
  const errorKey = params.error ?? null;
  const sourceFilter = params.source ?? null;
  const countryFilter = params.country ?? null;
  const categoryFilter = params.category ?? null;

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

  // ---- Build where clause ----
  const where: Record<string, string> = {};
  if (sourceFilter) where.sourceId = sourceFilter;
  if (countryFilter) where.countryId = countryFilter;
  if (categoryFilter) where.categoryId = categoryFilter;

  // ---- Query mappings with relation includes ----
  const mappings = await prisma.sourceMapping.findMany({
    where,
    orderBy: [
      { source: { name: "asc" } },
      { priority: "desc" },
    ],
    include: {
      source: { select: { id: true, name: true, sourceType: true } },
      country: { select: { id: true, name: true, code: true } },
      category: { select: { id: true, name: true, slug: true, level: true } },
    },
  });

  // Cast to row type
  const mappingRows: SourceMappingRow[] = mappings.map((m) => ({
    id: m.id,
    sourceId: m.sourceId,
    countryId: m.countryId,
    categoryId: m.categoryId,
    priority: m.priority,
    status: m.status,
    createdAt: m.createdAt,
    sourceName: m.source.name,
    sourceType: m.source.sourceType,
    countryName: m.country.name,
    countryCode: m.country.code,
    categoryName: m.category.name,
    categorySlug: m.category.slug,
    categoryLevel: m.category.level,
  }));

  // ---- Fetch dropdown options ----
  const [sources, countries, categories] = await Promise.all([
    prisma.source.findMany({
      select: { id: true, name: true, sourceType: true },
      orderBy: { name: "asc" },
    }),
    prisma.country.findMany({
      select: { id: true, name: true, code: true },
      orderBy: { name: "asc" },
    }),
    prisma.category.findMany({
      select: { id: true, name: true, slug: true, level: true },
      orderBy: { name: "asc" },
    }),
  ]);

  const sourceOptions = sources.map((s) => ({
    id: s.id,
    name: s.name,
    sourceType: s.sourceType,
  }));
  const countryOptions = countries.map((c) => ({
    id: c.id,
    name: c.name,
    code: c.code,
  }));
  const categoryOptions = categories.map((c) => ({
    id: c.id,
    name: c.name,
    slug: c.slug,
    level: c.level,
  }));

  // ---- Resolve edit mapping (if editing) ----
  const editMapping = editId
    ? await prisma.sourceMapping.findUnique({
        where: { id: editId },
        select: {
          id: true,
          sourceId: true,
          countryId: true,
          categoryId: true,
          priority: true,
          status: true,
        },
      })
    : null;

  const editMappingData = editMapping
    ? {
        id: editMapping.id,
        sourceId: editMapping.sourceId,
        countryId: editMapping.countryId,
        categoryId: editMapping.categoryId,
        priority: editMapping.priority,
        status: editMapping.status,
      }
    : null;

  return (
    <SourceMappingsPageClient
      mappings={mappingRows}
      sourceFilter={sourceFilter}
      countryFilter={countryFilter}
      categoryFilter={categoryFilter}
      sourceOptions={sourceOptions}
      countryOptions={countryOptions}
      categoryOptions={categoryOptions}
      editMapping={editMappingData}
      successMsg={successMsg}
      errorMsg={errorMsg}
    />
  );
}
