import Shortify, { DatabaseConfig } from "../src/index";

async function clickTrackingExample() {
  console.log("=== Click Tracking & Analytics Example ===");

  // Using SQLite for this example (no external dependencies needed)
  const dbConfig: DatabaseConfig = {
    type: "sqlite",
    database: "./click-tracking.db",
    maxRetries: 1,
    retryDelay: 100,
  };

  const shortify = new Shortify("https://short.ly", dbConfig);

  try {
    await shortify.connect();
    console.log("✅ Connected to database");

    // Create a test URL
    const result = await shortify.shorten(
      "https://www.example.com/product-page"
    );
    console.log("📝 Created shortened URL:", result.shortUrl);
    console.log("🆔 URL ID:", result.urlId);

    // Simulate multiple clicks by resolving the URL multiple times
    console.log("\n🖱️  Simulating user clicks...");

    for (let i = 1; i <= 5; i++) {
      const originalUrl = await shortify.resolve(result.urlId);
      console.log(`   Click ${i}: Resolved to ${originalUrl}`);
    }

    // Get detailed statistics
    console.log("\n📊 Getting detailed statistics...");
    const stats = await shortify.getStats(result.urlId);

    if (stats) {
      console.log("   📈 Total clicks:", stats.clicks);
      console.log("   📅 Created at:", stats.createdAt);
      console.log("   🔗 Original URL:", stats.originalUrl);
      console.log("   ⚡ Short URL:", stats.shortUrl);
      console.log("   🆔 URL ID:", stats.urlId);

      if (stats.expiresAt) {
        console.log("   ⏰ Expires at:", stats.expiresAt);
      } else {
        console.log("   ⏰ Expires at: Never (no expiration set)");
      }
    }

    // Create multiple URLs and track their performance
    console.log("\n📋 Creating multiple URLs for comparison...");

    const urls = [
      "https://www.example.com/page1",
      "https://www.example.com/page2",
      "https://www.example.com/page3",
    ];

    const urlResults: any[] = [];

    for (const url of urls) {
      const result = await shortify.shorten(url);
      urlResults.push(result);
      console.log(`   Created: ${result.shortUrl} for ${url}`);
    }

    // Simulate different click patterns
    console.log("\n🖱️  Simulating different click patterns...");

    // URL 1: High traffic (10 clicks)
    for (let i = 0; i < 10; i++) {
      await shortify.resolve(urlResults[0].urlId);
    }
    console.log(`   ${urlResults[0].shortUrl}: 10 clicks`);

    // URL 2: Medium traffic (5 clicks)
    for (let i = 0; i < 5; i++) {
      await shortify.resolve(urlResults[1].urlId);
    }
    console.log(`   ${urlResults[1].shortUrl}: 5 clicks`);

    // URL 3: Low traffic (2 clicks)
    for (let i = 0; i < 2; i++) {
      await shortify.resolve(urlResults[2].urlId);
    }
    console.log(`   ${urlResults[2].shortUrl}: 2 clicks`);

    // Compare performance
    console.log("\n📊 Performance Comparison:");
    for (const urlResult of urlResults) {
      const stats = await shortify.getStats(urlResult.urlId);
      if (stats) {
        console.log(`   ${urlResult.shortUrl}: ${stats.clicks} clicks`);
      }
    }

    // Create a URL with expiration and track clicks over time
    console.log("\n⏰ Creating URL with expiration...");
    const expiringUrl = await shortify.shorten(
      "https://www.example.com/limited-offer",
      {
        expiresInDays: 1,
      }
    );
    console.log(`   Created: ${expiringUrl.shortUrl} (expires in 1 day)`);

    // Simulate some clicks on the expiring URL
    for (let i = 0; i < 3; i++) {
      await shortify.resolve(expiringUrl.urlId);
    }

    const expiringStats = await shortify.getStats(expiringUrl.urlId);
    console.log(`   Clicks before expiration: ${expiringStats?.clicks}`);

    // Demonstrate URL deletion and its impact on stats
    console.log("\n🗑️  Demonstrating URL deletion...");
    const deleteUrl = await shortify.shorten(
      "https://www.example.com/temp-page"
    );
    console.log(`   Created: ${deleteUrl.shortUrl}`);

    // Add some clicks
    await shortify.resolve(deleteUrl.urlId);
    await shortify.resolve(deleteUrl.urlId);

    const beforeDeleteStats = await shortify.getStats(deleteUrl.urlId);
    console.log(`   Clicks before deletion: ${beforeDeleteStats?.clicks}`);

    // Delete the URL
    const deleted = await shortify.delete(deleteUrl.urlId);
    console.log(`   Deleted: ${deleted ? "Success" : "Failed"}`);

    // Try to get stats after deletion
    const afterDeleteStats = await shortify.getStats(deleteUrl.urlId);
    console.log(
      `   Stats after deletion: ${
        afterDeleteStats ? "Still available" : "Not found"
      }`
    );

    // Demonstrate custom URL ID with tracking
    console.log("\n🎯 Creating custom URL with tracking...");
    const customUrl = await shortify.shorten(
      "https://www.example.com/custom-page",
      {
        customUrlId: "my-custom-link",
      }
    );
    console.log(`   Custom URL: ${customUrl.shortUrl}`);
    console.log(`   Custom ID: ${customUrl.urlId}`);

    // Add clicks to custom URL
    for (let i = 0; i < 7; i++) {
      await shortify.resolve(customUrl.urlId);
    }

    const customStats = await shortify.getStats(customUrl.urlId);
    console.log(`   Custom URL clicks: ${customStats?.clicks}`);

    // Summary
    console.log("\n📈 Summary:");
    console.log(
      "   • Click tracking works automatically when URLs are resolved"
    );
    console.log(
      "   • Statistics include clicks, creation date, and expiration info"
    );
    console.log("   • URLs can be compared based on their click counts");
    console.log("   • Expiring URLs maintain click tracking until expiration");
    console.log("   • Deleted URLs lose their statistics");
    console.log("   • Custom URL IDs work with full tracking capabilities");

    await shortify.disconnect();
    console.log("\n✅ Disconnected from database");
  } catch (error) {
    console.error(
      "❌ Error:",
      error instanceof Error ? error.message : String(error)
    );
  }
}

// Run the example
clickTrackingExample();
