import { config } from "dotenv";
config({ path: ".env.local" });

import { db } from "../lib/admin/db";
import { formatLocationDisplay } from "../lib/admin/location-formatter";
import { blogService } from "../lib/blog-service";

async function runTests() {
  console.log("=== Testing Media Library & Content Activity History Upgrade ===");

  const sampleLocation = {
    status: "available" as const,
    address: "Jaipur, Rajasthan, India",
    city: "Jaipur",
    region: "Rajasthan",
    country: "India",
    latitude: 26.88403,
    longitude: 75.74335,
    source: "Browser Geolocation",
    capturedAt: new Date().toISOString(),
  };

  const actor = {
    id: "admin-test-01",
    name: "Main Administrator",
    email: "admin@qutoai.com",
    role: "MAIN_ADMIN",
    location: sampleLocation,
  };

  // Test 1: Location Formatter
  console.log("\n[Test 1] Testing Location Formatter...");
  const formattedAddr = formatLocationDisplay(sampleLocation);
  console.log("Formatted address:", formattedAddr);
  if (formattedAddr !== "Jaipur, Rajasthan, India") {
    throw new Error(`Expected "Jaipur, Rajasthan, India", got "${formattedAddr}"`);
  }

  const coordsOnlyLoc = {
    status: "available" as const,
    latitude: 26.884,
    longitude: 75.7433,
  };
  const formattedCoords = formatLocationDisplay(coordsOnlyLoc);
  console.log("Formatted coordinates fallback:", formattedCoords);
  if (!formattedCoords.includes("26.8840")) {
    throw new Error(`Expected coordinate fallback, got "${formattedCoords}"`);
  }

  const unavailableLoc = { status: "unavailable" as const };
  console.log("Unavailable formatted:", formatLocationDisplay(unavailableLoc));

  // Test 2: Upload Media Log
  console.log("\n[Test 2] Testing MEDIA_UPLOADED audit event...");
  const uploadLog = await db.logContentEvent({
    actorId: actor.id,
    actorName: actor.name,
    actorEmail: actor.email,
    actorRole: actor.role,
    location: actor.location,
    postId: null,
    postTitle: null,
    postSlug: null,
    action: "MEDIA_UPLOADED",
    details: {
      mediaId: "test-media-1",
      assetName: "voice-agent-banner.webp",
      publicId: "quto/media/voice-agent-banner",
      size: 45200,
      format: "image/webp",
      dimensions: "1200x630",
    },
  });

  console.log("Logged upload event ID:", uploadLog.id);
  const fetchedUpload = await db.getContentLogs({ limit: 1 });
  console.log("Latest log action:", fetchedUpload[0].action);
  console.log("Latest log location:", fetchedUpload[0].location);
  if (fetchedUpload[0].action !== "MEDIA_UPLOADED") {
    throw new Error(`Expected MEDIA_UPLOADED, got ${fetchedUpload[0].action}`);
  }
  if (!fetchedUpload[0].location || fetchedUpload[0].location.city !== "Jaipur") {
    throw new Error("Missing or invalid location in MongoDB content log!");
  }

  // Test 3: Media Replaced Log (NOT MEDIA_CHANGED)
  console.log("\n[Test 3] Testing MEDIA_REPLACED audit event...");
  const replaceLog = await db.logContentEvent({
    actorId: actor.id,
    actorName: actor.name,
    actorEmail: actor.email,
    actorRole: actor.role,
    location: actor.location,
    postId: null,
    postTitle: null,
    postSlug: null,
    action: "MEDIA_REPLACED",
    details: {
      mediaId: "test-media-1",
      oldAsset: {
        id: "test-media-1",
        name: "old-voice-agent.webp",
        publicId: "quto/media/old-voice-agent",
      },
      newAsset: {
        id: "test-media-1",
        name: "voice-agent-banner-v2.webp",
        publicId: "quto/media/voice-agent-banner-v2",
      },
    },
  });

  const fetchedReplace = await db.getContentLogs({ limit: 1 });
  console.log("Latest log action:", fetchedReplace[0].action);
  console.log("Old asset:", (fetchedReplace[0].details as any).oldAsset?.name);
  console.log("New asset:", (fetchedReplace[0].details as any).newAsset?.name);
  if (fetchedReplace[0].action !== "MEDIA_REPLACED") {
    throw new Error(`Expected MEDIA_REPLACED, got ${fetchedReplace[0].action}`);
  }

  // Test 4: Bulk Delete Log
  console.log("\n[Test 4] Testing MEDIA_BULK_DELETED audit event...");
  await db.logContentEvent({
    actorId: actor.id,
    actorName: actor.name,
    actorEmail: actor.email,
    actorRole: actor.role,
    location: actor.location,
    postId: null,
    postTitle: null,
    postSlug: null,
    action: "MEDIA_BULK_DELETED",
    details: {
      totalRequested: 5,
      deletedCount: 4,
      skippedCount: 1,
      deletedNames: ["img1.webp", "img2.webp", "img3.webp", "img4.webp"],
      skippedNames: ["referenced-hero.webp"],
      reasons: ["Referenced by 2 articles"],
    },
  });

  const fetchedBulk = await db.getContentLogs({ action: "MEDIA", limit: 1 });
  console.log("Fetched MEDIA categorized log:", fetchedBulk[0].action);
  console.log("Bulk delete details:", fetchedBulk[0].details);
  if (fetchedBulk[0].action !== "MEDIA_BULK_DELETED") {
    throw new Error(`Expected MEDIA_BULK_DELETED, got ${fetchedBulk[0].action}`);
  }

  // Test 5: Article Banner Change Audit
  console.log("\n[Test 5] Testing POST_BANNER_CHANGED audit event via blogService...");
  const draftPost = await blogService.createDraft(
    {
      title: "Voice AI Security Best Practices " + Date.now(),
      category: "Voice AI",
    },
    actor
  );
  console.log("Draft created:", draftPost.id, draftPost.title);

  // Update banner
  const updatedPost = await blogService.updateDraft(
    draftPost.id,
    {
      featuredImage: "https://res.cloudinary.com/demo/image/upload/voice-security-banner.webp",
      featuredImageAlt: "Voice AI Security Infrastructure Architecture",
    },
    actor
  );
  console.log("Updated draft with new banner:", updatedPost.featuredImage);

  const bannerLogs = await db.getContentLogs({ action: "POST_BANNER_CHANGED", limit: 1 });
  console.log("Banner log fetched:", bannerLogs[0]?.action);
  console.log("Banner log location:", bannerLogs[0]?.location);
  console.log("Banner log details:", bannerLogs[0]?.details);

  if (!bannerLogs[0] || bannerLogs[0].action !== "POST_BANNER_CHANGED") {
    throw new Error("Expected POST_BANNER_CHANGED event not found!");
  }
  if (!bannerLogs[0].location || bannerLogs[0].location.city !== "Jaipur") {
    throw new Error("Missing location in POST_BANNER_CHANGED event!");
  }

  // Cleanup test draft
  await db.deletePost(draftPost.id);
  console.log("Cleaned up test draft post.");

  console.log("\n✅ ALL TESTS PASSED SUCCESSFULLY!");
  process.exit(0);
}

runTests().catch((err) => {
  console.error("\n❌ TEST FAILED:", err);
  process.exit(1);
});
