import fs from "fs";
import path from "path";

// Ensure .env variables are loaded from disk if not already set
try {
  const envPath = path.resolve(process.cwd(), ".env");
  if (fs.existsSync(envPath)) {
    const envLines = fs.readFileSync(envPath, "utf-8").split("\n");
    for (const line of envLines) {
      const trimmed = line.trim();
      if (!trimmed || trimmed.startsWith("#")) continue;
      const eqIdx = trimmed.indexOf("=");
      if (eqIdx > 0) {
        const key = trimmed.substring(0, eqIdx).trim();
        let val = trimmed.substring(eqIdx + 1).trim();
        if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
          val = val.substring(1, val.length - 1);
        }
        if (process.env[key] === undefined) {
          process.env[key] = val;
        }
      }
    }
  }
} catch (e) {
  // Ignore
}

import prisma from "../app/db.server";
import { decryptToken } from "../app/lib/security/encryption";
import { migrateLegacyOfflineToken } from "../app/services/token-manager.server";

async function main() {
  console.log("==================================================================");
  console.log("🚀 SHOPIPILOT AI: BULK MIGRATION TO EXPIRING OFFLINE ACCESS TOKENS");
  console.log("==================================================================\n");

  const allShops = await prisma.shop.findMany({
    orderBy: { createdAt: "desc" },
  });

  console.log(`Found ${allShops.length} total store records in database.\n`);

  let alreadyExpiring = 0;
  let uninstalledCount = 0;
  let migratedCount = 0;
  let failedCount = 0;

  for (const shop of allShops) {
    const domain = shop.shopifyDomain;

    // Check if store is uninstalled
    if (shop.uninstalledAt || !shop.accessToken || shop.accessToken === "shpss_sample_token") {
      console.log(`⚪ [SKIPPED] ${domain} - Store uninstalled or sample token`);
      uninstalledCount++;
      continue;
    }

    // Check if store already has a valid expiring token + refresh token
    if (shop.refreshToken && shop.tokenExpiresAt) {
      console.log(`✅ [ALREADY COMPLIANT] ${domain} - Has refreshToken & expiresAt: ${shop.tokenExpiresAt.toISOString()}`);
      alreadyExpiring++;
      continue;
    }

    // Attempt token migration for legacy token
    let rawToken = "";
    try {
      rawToken = decryptToken(shop.accessToken.trim());
    } catch {
      rawToken = shop.accessToken.trim();
    }

    if (!rawToken || rawToken === "shpss_sample_token") {
      console.log(`⚪ [SKIPPED] ${domain} - No valid raw token found`);
      uninstalledCount++;
      continue;
    }

    console.log(`🔄 [MIGRATING] ${domain}...`);
    const result = await migrateLegacyOfflineToken(domain, rawToken, shop.scopes);

    if (result && result.accessToken) {
      console.log(
        `   ✨ SUCCESS! Migrated to expiring token. Expires at: ${result.tokenExpiresAt?.toISOString() || "1 hour"}`
      );
      migratedCount++;
    } else {
      console.log(
        `   ⚠️ COULD NOT MIGRATE: Store may be inactive, dev store deleted, or token already revoked by merchant.`
      );
      failedCount++;
    }
  }

  console.log("\n==================================================================");
  console.log("MIGRATION SUMMARY:");
  console.log(`Total Stores:               ${allShops.length}`);
  console.log(`Already Expiring / Rotated: ${alreadyExpiring}`);
  console.log(`Newly Migrated:             ${migratedCount}`);
  console.log(`Uninstalled / Inactive:     ${uninstalledCount}`);
  console.log(`Failed / Revoked:           ${failedCount}`);
  console.log("==================================================================\n");
}

main()
  .catch((e) => {
    console.error("Migration failed with error:", e);
    process.exit(1);
  })
  .finally(() => prisma.$disconnect());
