/**
 * Centralized country/region platform availability.
 * Combines registry defaults, env overrides, and project target countries.
 */

import {
  getPlatformCapability,
  SOCIAL_PLATFORM_IDS,
  type SocialPlatformId,
} from "@/lib/social/config/platform-registry";
import { getPlatformIntegrationReport } from "@/lib/social/config/social-config";

export type PlatformAvailabilityReason =
  | "available"
  | "platform_disabled"
  | "missing_credentials"
  | "not_implemented"
  | "coming_soon"
  | "country_blocked"
  | "country_unsupported";

export interface PlatformCountryAvailability {
  platform: SocialPlatformId;
  available: boolean;
  reason: PlatformAvailabilityReason;
  message: string;
  /** Countries from the project that caused a block (if any). */
  conflictingCountries: string[];
  blockedCountries: string[];
  supportedCountries: string[] | "*";
}

function parseCountryList(raw: string | undefined): string[] | null {
  if (raw === undefined) return null;
  const trimmed = raw.trim();
  if (!trimmed) return [];
  if (trimmed === "*") return null; // signal "use registry default / allow all"
  return trimmed
    .split(/[,;\s]+/)
    .map((c) => c.trim().toUpperCase())
    .filter(Boolean);
}

/** Effective blocked countries = env override ?? registry default. */
export function getBlockedCountriesForPlatform(platform: SocialPlatformId): string[] {
  const cap = getPlatformCapability(platform);
  if (!cap) return [];
  const envKey = `PLATFORM_BLOCKED_COUNTRIES_${platform.toUpperCase()}`;
  const fromEnv = parseCountryList(process.env[envKey]);
  if (fromEnv !== null) return fromEnv;
  return [...cap.blockedCountries];
}

/** Effective allowed list — null means all (minus blocked). */
export function getSupportedCountriesForPlatform(
  platform: SocialPlatformId,
): string[] | "*" {
  const cap = getPlatformCapability(platform);
  if (!cap) return [];
  const envKey = `PLATFORM_ALLOWED_COUNTRIES_${platform.toUpperCase()}`;
  const fromEnv = parseCountryList(process.env[envKey]);
  if (fromEnv !== null) {
    return fromEnv.length === 0 ? "*" : fromEnv;
  }
  return cap.supportedCountries;
}

function normalizeProjectCountries(countries: string[] | undefined | null): string[] {
  if (!countries?.length) return [];
  return countries.map((c) => c.trim().toUpperCase()).filter(Boolean);
}

/**
 * Resolve whether a platform may be offered / connected / published for a
 * project's target countries. Does not invent availability — uses registry + env.
 */
export function resolvePlatformCountryAvailability(
  platform: SocialPlatformId,
  projectCountries?: string[] | null,
): PlatformCountryAvailability {
  const report = getPlatformIntegrationReport(platform);
  const blocked = getBlockedCountriesForPlatform(platform);
  const supported = getSupportedCountriesForPlatform(platform);
  const countries = normalizeProjectCountries(projectCountries);

  const base = {
    platform,
    blockedCountries: blocked,
    supportedCountries: supported,
    conflictingCountries: [] as string[],
  };

  if (report.status === "coming_soon") {
    return {
      ...base,
      available: false,
      reason: "coming_soon",
      message: `${report.label} is not available in this release.`,
    };
  }
  if (report.status === "not_implemented") {
    return {
      ...base,
      available: false,
      reason: "not_implemented",
      message: `${report.label} API integration is not implemented.`,
    };
  }
  if (report.status === "disabled") {
    return {
      ...base,
      available: false,
      reason: "platform_disabled",
      message: `${report.label} is disabled in environment configuration.`,
    };
  }
  if (report.status === "missing_credentials") {
    return {
      ...base,
      available: false,
      reason: "missing_credentials",
      message: `${report.label} OAuth credentials are incomplete.`,
    };
  }

  // No project countries yet — treat as available (user can still connect).
  if (!countries.length) {
    return {
      ...base,
      available: true,
      reason: "available",
      message: `${report.label} is available.`,
    };
  }

  const hitBlocked = countries.filter((c) => blocked.includes(c));
  if (hitBlocked.length) {
    return {
      ...base,
      available: false,
      reason: "country_blocked",
      conflictingCountries: hitBlocked,
      message: `${report.label} is not available in: ${hitBlocked.join(", ")}.`,
    };
  }

  if (supported !== "*") {
    const unsupported = countries.filter((c) => !supported.includes(c));
    if (unsupported.length === countries.length) {
      return {
        ...base,
        available: false,
        reason: "country_unsupported",
        conflictingCountries: unsupported,
        message: `${report.label} is not supported for selected regions: ${unsupported.join(", ")}.`,
      };
    }
  }

  return {
    ...base,
    available: true,
    reason: "available",
    message: `${report.label} is available for the selected regions.`,
  };
}

export function listPlatformAvailabilityForCountries(
  projectCountries?: string[] | null,
): PlatformCountryAvailability[] {
  return SOCIAL_PLATFORM_IDS.map((id) =>
    resolvePlatformCountryAvailability(id, projectCountries),
  );
}

/** Platforms the UI may show as connectable for this project. */
export function listConnectablePlatformIds(
  projectCountries?: string[] | null,
): SocialPlatformId[] {
  return listPlatformAvailabilityForCountries(projectCountries)
    .filter((a) => a.available)
    .map((a) => a.platform);
}
