/**
 * One-off backfill: populate products.notions_cost_each and supplier_cost_each
 * from MySQL supplier_item_data. Idempotent — safe to re-run.
 *
 * Usage (on the server, where the SSH tunnel and env are configured):
 *   cd /var/www/inventory && node scripts/backfill-supplier-costs.js
 *
 * After this lands, the daily products import (via syncSupplierCosts in
 * scripts/import/products.js) keeps the columns up to date.
 */

const dotenv = require("dotenv");
const path = require("path");
dotenv.config({ path: path.join(__dirname, "../.env") });

const { setupConnections, closeConnections } = require("./import/utils");
const { syncSupplierCosts } = require("./import/products");

const sshConfig = {
  ssh: {
    host: process.env.PROD_SSH_HOST,
    port: process.env.PROD_SSH_PORT || 22,
    username: process.env.PROD_SSH_USER,
    privateKey: process.env.PROD_SSH_KEY_PATH
      ? require("fs").readFileSync(process.env.PROD_SSH_KEY_PATH)
      : undefined,
    compress: true,
  },
  prodDbConfig: {
    host: process.env.PROD_DB_HOST || "localhost",
    user: process.env.PROD_DB_USER,
    password: process.env.PROD_DB_PASSWORD,
    database: process.env.PROD_DB_NAME,
    port: process.env.PROD_DB_PORT || 3306,
    timezone: "-05:00",
  },
  localDbConfig: {
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    port: process.env.DB_PORT || 5432,
    ssl: process.env.DB_SSL === "true",
    connectionTimeoutMillis: 60000,
    idleTimeoutMillis: 30000,
    max: 4,
  },
};

(async () => {
  let connections;
  const start = Date.now();
  try {
    console.log("Setting up connections...");
    connections = await setupConnections(sshConfig);
    const { prodConnection, localConnection } = connections;

    console.log("Starting transaction...");
    await localConnection.beginTransaction();

    const result = await syncSupplierCosts(prodConnection, localConnection);

    await localConnection.commit();
    console.log(`Done. Updated ${result.updated} rows in ${(Date.now() - start) / 1000}s`);
  } catch (err) {
    console.error("Backfill failed:", err);
    if (connections?.localConnection?._transactionActive) {
      try { await connections.localConnection.rollback(); } catch (e) {}
    }
    process.exitCode = 1;
  } finally {
    if (connections) {
      try { await closeConnections(connections); } catch (e) { console.error("Close error:", e); }
    }
    process.exit();
  }
})();
