import { NextResponse } from "next/server";
import { runRoleAutomation } from "@/lib/role-automation/executor";
import type { Business, RoleGroups } from "@/lib/types";

export async function POST(req: Request) {
  try {
    const { business, roleName, roleGroup, taskId, taskIds } = (await req.json()) as {
      business: Business;
      roleName: string;
      roleGroup?: keyof RoleGroups;
      taskId?: string;
      taskIds?: string[];
    };

    if (!business || !roleName) {
      return NextResponse.json({ error: "business and roleName are required" }, { status: 400 });
    }

    const ids = taskIds ?? (taskId ? [taskId] : undefined);
    const run = runRoleAutomation(business, roleName, roleGroup, ids);
    return NextResponse.json({ run });
  } catch {
    return NextResponse.json({ error: "Failed to run role automation" }, { status: 500 });
  }
}
