import { NextResponse } from "next/server";
import { getSessionUser } from "@/lib/auth/get-session-user";
import {
  getFacebookDestinationCapabilities,
  getLinkedInDestinationHints,
  isSocialMediaGloballyEnabled,
  listPlatformIntegrationReports,
} from "@/lib/social/config/social-config";
import { SOCIAL_PLATFORM_REGISTRY } from "@/lib/social/config/platform-registry";
import { resolvePlatformCountryAvailability } from "@/lib/social/config/platform-availability";

/**
 * Server-side platform integration status (env flags + credentials + country + registry).
 * Does not expose secrets — only configured:true/false and missing key names.
 *
 * Query: ?countries=IN,US (optional ISO codes from the active project)
 */
export async function GET(request: Request) {
  const user = await getSessionUser();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { searchParams } = new URL(request.url);
  const countriesRaw = searchParams.get("countries") ?? "";
  const countries = countriesRaw
    .split(/[,;\s]+/)
    .map((c) => c.trim().toUpperCase())
    .filter(Boolean);

  const reports = listPlatformIntegrationReports();
  const platforms = reports.map((p) => {
    const country = resolvePlatformCountryAvailability(p.platform, countries);
    const ready =
      p.status === "enabled" && country.available
        ? "ready"
        : !country.available &&
            (country.reason === "country_blocked" || country.reason === "country_unsupported")
          ? country.reason
          : p.readiness;

    return {
      platform: p.platform,
      label: p.label,
      implemented: p.implemented,
      enabled: p.envEnabled && p.status === "enabled" && country.available,
      envEnabled: p.envEnabled,
      credentialsConfigured: p.credentialsConfigured,
      connectionRequired: p.connectionRequired,
      supportsOAuth: p.supportsOAuth && country.available,
      supportsPublish: p.supportsPublish && country.available,
      supportedDestinations: p.supportedDestinations,
      supportedContentTypes: p.supportedContentTypes,
      destinations: p.destinations,
      contentTypes: p.contentTypes,
      mediaRules: SOCIAL_PLATFORM_REGISTRY[p.platform].mediaRules,
      status: ready,
      integrationStatus: p.status,
      countryAvailable: country.available,
      countryReason: country.reason,
      countryMessage: country.message,
      blockedCountries: country.blockedCountries,
      notes: [
        ...p.notes,
        ...(country.available ? [] : [country.message]),
      ],
      missingEnv: p.missingEnv,
      requiredEnv: p.requiredEnv,
    };
  });

  const byId: Record<string, (typeof platforms)[number]> = {};
  for (const p of platforms) {
    byId[p.platform] = p;
  }

  return NextResponse.json({
    socialMediaEnabled: isSocialMediaGloballyEnabled(),
    countries,
    platforms,
    /** Convenience map keyed by platform id */
    ...byId,
    registry: Object.fromEntries(
      Object.entries(SOCIAL_PLATFORM_REGISTRY).map(([id, cap]) => [
        id,
        {
          implemented: cap.implemented,
          defaultEnabled: cap.defaultEnabled,
          destinations: cap.destinations,
          contentTypes: cap.contentTypes,
          oauthRequired: cap.oauthRequired,
          mediaRules: cap.mediaRules,
          supportedCountries: cap.supportedCountries,
          blockedCountries: cap.blockedCountries,
        },
      ]),
    ),
    destinations: {
      facebook: getFacebookDestinationCapabilities(),
      linkedin: getLinkedInDestinationHints(),
    },
  });
}
