import { NextRequest, NextResponse } from "next/server";
import {
  executeScript,
  getScriptExecution,
} from "../../../services/bashExecService";

// Modified POST method that returns a token instead of waiting for execution result
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { scriptPath, args } = body;

    if (!scriptPath) {
      return NextResponse.json(
        { error: "Script path is required" },
        { status: 400 },
      );
    }

    const token = executeScript({
      scriptPath,
      args,
    });

    return NextResponse.json({ token });
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

// API to query execution result by token from path parameter
export async function GET(request: NextRequest) {
  try {
    // Get token from the search params in the URL
    const { searchParams } = new URL(request.url);
    const token = searchParams.get("token");

    if (!token) {
      return NextResponse.json(
        { error: "Token is required as a query parameter" },
        { status: 400 },
      );
    }

    const execution = getScriptExecution(token);
    return NextResponse.json(execution);
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
