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

async function main() {
  console.log("Deploying to local 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
  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();

  await shipmentTracker.grantRole(MANUFACTURER_ROLE, deployer.address);
  console.log("MANUFACTURER_ROLE granted to:", deployer.address);

  await shipmentTracker.grantRole(BUYER_ROLE, deployer.address);
  console.log("BUYER_ROLE granted to:", deployer.address);

  await shipmentTracker.grantRole(LOGISTICS_ROLE, deployer.address);
  console.log("LOGISTICS_ROLE granted to:", deployer.address);

  // Save deployment info
  const deploymentInfo = {
    network: "localhost",
    chainId: (await ethers.provider.getNetwork()).chainId.toString(),
    deployer: deployer.address,
    contracts: {
      ShipmentTracker: {
        address: shipmentTrackerAddress,
        deployedAt: new Date().toISOString()
      }
    }
  };

  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, "localhost.json"),
    JSON.stringify(deploymentInfo, null, 2)
  );

  console.log("\n=== Deployment Summary ===");
  console.log("Network:", "localhost");
  console.log("Chain ID:", deploymentInfo.chainId);
  console.log("Deployer:", deployer.address);
  console.log("\nContracts:");
  console.log("  ShipmentTracker:", shipmentTrackerAddress);
  console.log("\nDeployment info saved to: deployments/localhost.json");

  // Create a test shipment
  console.log("\n--- Creating Test Shipment ---");
  const tx = await shipmentTracker.createShipment(
    "TEST-001",
    deployer.address,
    "Test Manufacturer",
    "MFG-001",
    deployer.address,
    "Test Buyer",
    "BYR-001",
    ethers.keccak256(ethers.toUtf8Bytes("test shipment data"))
  );
  const receipt = await tx.wait();
  console.log("Test shipment created! Transaction hash:", receipt.hash);

  const shipmentId = await shipmentTracker.getShipmentByExternalId("TEST-001");
  console.log("Shipment ID:", shipmentId.toString());
}

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