/**
 * Platform availability + content validation tests (no live API calls).
 * Run: npx tsx scripts/test-platform-availability.ts
 */
import {
  resolvePlatformCountryAvailability,
  getBlockedCountriesForPlatform,
} from "../src/lib/social/config/platform-availability";
import { validateContentForPlatform } from "../src/lib/social/validate-publish-content";
import { SOCIAL_PLATFORM_REGISTRY } from "../src/lib/social/config/platform-registry";

let passed = 0;
let failed = 0;

function assert(name: string, cond: boolean, detail?: string) {
  if (cond) {
    passed += 1;
    console.log(`PASS  ${name}`);
  } else {
    failed += 1;
    console.log(`FAIL  ${name}${detail ? ` — ${detail}` : ""}`);
  }
}

// TikTok blocked in India by default (country list — independent of ENABLED flag)
assert(
  "TikTok blockedCountries includes IN",
  getBlockedCountriesForPlatform("tiktok").includes("IN"),
);

// Simulate enabled path: country gate after env would be country_blocked
process.env.TIKTOK_ENABLED = "true";
process.env.TIKTOK_CLIENT_KEY = "test-key";
process.env.TIKTOK_CLIENT_SECRET = "test-secret";
const tiktokIn = resolvePlatformCountryAvailability("tiktok", ["IN"]);
assert(
  "TikTok unavailable for IN when enabled",
  !tiktokIn.available && tiktokIn.reason === "country_blocked",
  tiktokIn.reason,
);
delete process.env.TIKTOK_ENABLED;
delete process.env.TIKTOK_CLIENT_KEY;
delete process.env.TIKTOK_CLIENT_SECRET;

const tiktokUs = resolvePlatformCountryAvailability("tiktok", ["US"]);
assert(
  "TikTok not country-blocked for US",
  tiktokUs.reason !== "country_blocked",
  tiktokUs.reason,
);

// Content validation
const pinNoImage = validateContentForPlatform({
  platform: "pinterest",
  caption: "Hello pin",
  imageUrl: null,
});
assert("Pinterest rejects missing image", !pinNoImage.ok);

const ytNoVideo = validateContentForPlatform({
  platform: "youtube",
  caption: "My video",
  videoUrl: null,
});
assert("YouTube rejects missing video", !ytNoVideo.ok);

const threadsOk = validateContentForPlatform({
  platform: "threads",
  caption: "Short update",
  imageUrl: null,
});
// May fail on missing_credentials / disabled — still should not claim IMAGE_REQUIRED
assert(
  "Threads text-only is allowed by media rules",
  !threadsOk.issues.some((i) => i.code === "IMAGE_REQUIRED"),
);

assert(
  "Registry has media rules for all platforms",
  Object.values(SOCIAL_PLATFORM_REGISTRY).every((p) => p.mediaRules?.maxCaptionLength > 0),
);

console.log(`\n${passed} passed, ${failed} failed`);
process.exit(failed ? 1 : 0);
