// =============================================================================
// HeadlineSift.com — Countries Admin Page
// =============================================================================
// Server component — queries Prisma, reads searchParams, renders the CRUD UI.

import type { Metadata } from "next";
import { prisma } from "@/lib/db/client";
import { CountriesPageClient } from "./CountriesPageClient";
import type { CountryRow } from "./CountryTable";

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

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

interface CountriesPageProps {
  searchParams: Promise<{
    search?: string;
    edit?: string;
    success?: string;
    error?: string;
  }>;
}

// Clean up success/error messages from searchParams
function successMessage(key: string): string | null {
  const messages: Record<string, string> = {
    created: "Country created successfully.",
    updated: "Country updated successfully.",
    deleted: "Country deleted successfully.",
    activated: "Country activated — it will appear in filters and assignments.",
    deactivated: "Country deactivated — it will be hidden from filters and assignments.",
  };
  return messages[key] ?? null;
}

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

export default async function CountriesPage({ searchParams }: CountriesPageProps) {
  const params = await searchParams;
  const search = params.search?.trim() ?? "";
  const editId = params.edit ?? null;
  const successKey = params.success ?? null;
  const errorKey = params.error ?? null;

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

  // ---- Query countries ----
  const where = search
    ? {
        OR: [
          { name: { contains: search } },
          { code: { contains: search.toUpperCase() } },
        ],
      }
    : {};

  const countries = await prisma.country.findMany({
    where,
    orderBy: [{ displayOrder: "asc" }, { name: "asc" }],
    select: {
      id: true,
      name: true,
      code: true,
      region: true,
      defaultLanguage: true,
      isGlobal: true,
      status: true,
      displayOrder: true,
      createdAt: true,
  },
  });

  // ---- Resolve dependent counts for each country ----
  const countriesWithDependents: CountryRow[] = await Promise.all(
    countries.map(async (c) => {
      const [sourceMappingCount, rawArticleCount, storyClusterCount, rankingRuleCount] =
        await Promise.all([
          prisma.sourceMapping.count({ where: { countryId: c.id } }),
          prisma.rawArticle.count({ where: { countryId: c.id } }),
          prisma.storyCluster.count({ where: { countryId: c.id } }),
          prisma.rankingRule.count({ where: { countryId: c.id } }),
        ]);

      return {
        ...c,
        dependentCount:
          sourceMappingCount + rawArticleCount + storyClusterCount + rankingRuleCount,
      };
    }),
  );

  // ---- Resolve edit country (if editing) ----
  const editCountry = editId
    ? await prisma.country.findUnique({
        where: { id: editId },
        select: {
          id: true,
          name: true,
          code: true,
          region: true,
          defaultLanguage: true,
          isGlobal: true,
          status: true,
          displayOrder: true,
        },
      })
    : null;

  // Edge case: edit ID in URL but country doesn't exist
  const editCountryData =
    editCountry
      ? {
          id: editCountry.id,
          name: editCountry.name,
          code: editCountry.code,
          region: editCountry.region,
          defaultLanguage: editCountry.defaultLanguage,
          isGlobal: editCountry.isGlobal,
          status: editCountry.status,
          displayOrder: editCountry.displayOrder,
        }
      : null;

  return (
    <CountriesPageClient
      countries={countriesWithDependents}
      searchQuery={search}
      editCountry={editCountryData}
      successMsg={successMsg}
      errorMsg={errorMsg}
    />
  );
}
