const { ethers, upgrades } = require("hardhat");

async function main() {
  console.log("Deploying to Optovia private network...");

  const [deployer] = await ethers.getSigners();
  console.log("Deploying contracts with account:", deployer.address);
  console.log("Account balance:", (await ethers.provider.getBalance(deployer.address)).toString());

  // Deploy ShipmentTracker
  console.log("\n--- Deploying ShipmentTracker (Upgradeable) ---");
  const ShipmentTracker = await ethers.getContractFactory("ShipmentTracker");
  const shipmentTracker = await upgrades.deployProxy(
    ShipmentTracker,
    [deployer.address],
    { initializer: "initialize" }
  );
  await shipmentTracker.waitForDeployment();
  const shipmentTrackerAddress = await shipmentTracker.getAddress();
  console.log("ShipmentTracker deployed to:", shipmentTrackerAddress);

  // Grant roles to platform services
  console.log("\nGranting roles...");
  const MANUFACTURER_ROLE = await shipmentTracker.MANUFACTURER_ROLE();
  const BUYER_ROLE = await shipmentTracker.BUYER_ROLE();
  const LOGISTICS_ROLE = await shipmentTracker.LOGISTICS_ROLE();

  // These addresses should be replaced with actual service addresses
  const platformServiceAddress = deployer.address; // Replace with actual platform service address

  await shipmentTracker.grantRole(MANUFACTURER_ROLE, platformServiceAddress);
  console.log("MANUFACTURER_ROLE granted to platform service:", platformServiceAddress);

  await shipmentTracker.grantRole(BUYER_ROLE, platformServiceAddress);
  console.log("BUYER_ROLE granted to platform service:", platformServiceAddress);

  await shipmentTracker.grantRole(LOGISTICS_ROLE, platformServiceAddress);
  console.log("LOGISTICS_ROLE granted to platform service:", platformServiceAddress);

  // Save deployment info
  const deploymentInfo = {
    network: "optovia-private",
    chainId: "1337",
    deployer: deployer.address,
    platformService: platformServiceAddress,
    contracts: {
      ShipmentTracker: {
        address: shipmentTrackerAddress,
        deployedAt: new Date().toISOString()
      }
    },
    roles: {
      ShipmentTracker: {
        MANUFACTURER_ROLE: MANUFACTURER_ROLE,
        BUYER_ROLE: BUYER_ROLE,
        LOGISTICS_ROLE: LOGISTICS_ROLE
      }
    }
  };

  const fs = require("fs");
  const path = require("path");
  const deploymentsDir = path.join(__dirname, "..", "deployments");

  if (!fs.existsSync(deploymentsDir)) {
    fs.mkdirSync(deploymentsDir, { recursive: true });
  }

  fs.writeFileSync(
    path.join(deploymentsDir, "optovia-private.json"),
    JSON.stringify(deploymentInfo, null, 2)
  );

  console.log("\n=== Deployment Summary ===");
  console.log("Network: Optovia Private Network");
  console.log("Chain ID: 1337");
  console.log("Deployer:", deployer.address);
  console.log("Platform Service:", platformServiceAddress);
  console.log("\nContracts:");
  console.log("  ShipmentTracker:", shipmentTrackerAddress);
  console.log("\nDeployment info saved to: deployments/optovia-private.json");

  console.log("\n--- Integration Instructions ---");
  console.log("1. Update backend configuration with contract address:");
  console.log(`   SHIPMENT_TRACKER_ADDRESS=${shipmentTrackerAddress}`);
  console.log("2. Configure blockchain RPC endpoint:");
  console.log("   BLOCKCHAIN_RPC_URL=http://besu-node1:8545");
  console.log("3. Store private key securely for platform service");
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });
