/**
 * Auto-provision/deprovision AMD users based on Rippling employee events.
 * Uses browse CLI for AMD UI automation (no REST API for user management).
 */

import { execSync } from "child_process";

interface ProvisionRequest {
  name: string;
  email: string;
  title: string;
  department: string;
  team: string;
}

function inferAmdRole(title: string, department: string, team: string): string {
  const t = title.toUpperCase();
  if (t.includes("BILLING") || t.includes("AR")) return "BILLING";
  if (t.includes("ADMIN") || t.includes("COO") || t.includes("CEO")) return "ADMIN";
  if (t.includes("MA") || t.includes("MEDICAL ASSISTANT") || t.includes("NURSE")) return "MEDICAL ASSISTANT";
  return "MEDICAL ASSISTANT";
}

function inferAmdUserType(title: string): string[] {
  const t = title.toUpperCase();
  if (t.includes("BILLING")) return ["PM"];
  if (t.includes("PROVIDER") || t.includes("MD") || t.includes("NP") || t.includes("LPC") || t.includes("THERAPIST")) return ["PM", "EHR"];
  return ["PM", "EHR"];
}

export async function provisionAmdUser(req: ProvisionRequest): Promise<{ success: boolean; message: string }> {
  const role = inferAmdRole(req.title, req.department, req.team);
  const userTypes = inferAmdUserType(req.title);
  const username = req.name.split(" ")[0].toUpperCase().slice(0, 8);

  return {
    success: false,
    message: `AMD user provisioning requires browse CLI automation. Proposed: username=${username}, role=${role}, types=${userTypes.join("+")}. Use /autobrowse or manual creation via AMD > System Settings > User Management.`,
  };
}

export async function deprovisionAmdUser(identifier: string): Promise<{ success: boolean; message: string }> {
  return {
    success: false,
    message: `AMD user deprovisioning requires browse CLI automation. User "${identifier}" should be disabled (not deleted) via AMD > System Settings > User Management.`,
  };
}
