#!/usr/bin/env node

const fs = require("fs");
const path = require("path");
const readline = require("readline");
const { execSync } = require("child_process");

// Create interface
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

console.log("\nSelect project to create:\n");
console.log("1. SIMS (Stock Inventory Management System)");
console.log("2. HMS (Hospital Management System)");
console.log("3. CIMS (Customer Information Management System)");
console.log("4. CRMS (Car Repair Management System)");
console.log("5. CWMS (Car Wash Management System)");
console.log("6. SIMS (Stock Inventory Management System with(MYSQL)\n");

// Ask user
rl.question("Enter your choice: ", (choice) => {

  let templateName = "";
  let projectName = "";

  switch (choice) {
    case "1":
      templateName = "SIMS";
      projectName = "sims-app";
      break;

    case "2":
      templateName = "HMS";
      projectName = "hms-app";
      break;

    case "3":
      templateName = "CIMS";
      projectName = "cims-app";
      break;

    case "4":
      templateName = "CRMS";
      projectName = "crms-app";
      break;

    case "5":
      templateName = "CWMS";
      projectName = "cwms-app";
      break;

    case "6":
        templateName = "SIMS2";
        projectName = "sims-app";
        break;
  

    default:
      console.log(" Invalid choice");
      rl.close();
      return;
  }

  const targetPath = path.join(process.cwd(), projectName);
  const templatePath = path.resolve(__dirname, "../templates", templateName);

  if (!fs.existsSync(templatePath)) {
    console.log(" Template not found:", templatePath);
    rl.close();
    return;
  }

  if (fs.existsSync(targetPath)) {
    console.log(` Folder "${projectName}" already exists`);
    rl.close();
    return;
  }

  try {
    // Create folder
    fs.mkdirSync(targetPath, { recursive: true });

    // Copy template
    fs.cpSync(templatePath, targetPath, { recursive: true });

    console.log(`\n ${projectName} created successfully!`);
    console.log(" Location:", targetPath);

    // Install dependencies (IMPORTANT for npx usability)
    console.log("\n Installing dependencies...\n");
    execSync(`cd ${targetPath} && npm install`, { stdio: "inherit" });

    console.log("\n Setup complete!");
    console.log(`\n Run your project:`);
    console.log(` cd ${projectName}`);
    console.log(` npm run dev\n`);

  } catch (error) {
    console.log(" Error:", error.message);
  }

  rl.close();
});