import { verifySession } from "@/lib/auth";
import {
  pgGetCurrencies,
  pgGetDefaultCurrency,
  pgGetExchangeRateSources,
  pgGetSettings,
} from "@/lib/postgres/data-access";
import { getTranslations, getCurrentLocale } from "@/lib/i18n";
import CurrenciesManagement from "@/components/admin/currencies-management";
import type { Currency } from "@/lib/types";

function isCurrency(value: unknown): value is Currency {
  if (!value || typeof value !== "object") return false;
  const item = value as Record<string, unknown>;
  return (
    typeof item.id === "string"
    && typeof item.code === "string"
    && typeof item.name === "string"
    && typeof item.nameEn === "string"
    && typeof item.symbol === "string"
  );
}

function normalizeExchangeRateSources(value: unknown): string[] {
  if (!Array.isArray(value)) return [];
  return value.filter((entry): entry is string => typeof entry === "string" && entry.trim().length > 0);
}

export default async function ManageCurrenciesPage() {
  const session = await verifySession();
  const user = session.user;
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tGlobal = t.Global || {};
  const tGeneralSettings = t.GeneralSettings || {};

  if (!user || user.role !== "admin") {
    return (
      <div className="text-center">
        <h1 className="text-2xl font-bold">{tGlobal?.accessDenied ?? "الوصول مرفوض"}</h1>
        <p>{tGlobal?.noPermission ?? "ليس لديك صلاحية لعرض هذه الصفحة."}</p>
      </div>
    );
  }

  const rawCurrencies: unknown[] = (await pgGetCurrencies({ page: 1, pageSize: 5000 })).items;
  const currencies: Currency[] = rawCurrencies.filter(isCurrency);

  const rawDefaultCurrency = await pgGetDefaultCurrency();
  const defaultCurrency = isCurrency(rawDefaultCurrency) ? rawDefaultCurrency : undefined;

  const rawExchangeRateSources = (await pgGetExchangeRateSources({ page: 1, pageSize: 5000 })).items;
  const exchangeRateSources = normalizeExchangeRateSources(rawExchangeRateSources);

  const settings = await pgGetSettings() as Record<string, unknown>;
  const appCurrency = String(settings.appCurrency || '');
  const currentCurrencyCode = currencies.some((c) => c.code === appCurrency)
    ? appCurrency
    : (defaultCurrency?.code || "USD");

  return (
    <CurrenciesManagement
      t={tGeneralSettings}
      tGlobal={tGlobal}
      currencies={currencies}
      currentCurrencyCode={currentCurrencyCode}
      exchangeRateSources={exchangeRateSources}
    />
  );
}
