import { NextResponse } from "next/server";
import { getActiveAccountProfile } from "@/lib/account-context";
import { runTaskForAccount } from "@/lib/automation/engine";
import { AUTOMATION_TASK_TYPES, type AutomationTaskType } from "@/lib/automation/types";
import { apiRouteErrorResponse } from "@/lib/auth/api";

export const maxDuration = 300;

export async function POST(request: Request) {
  try {
    const account = await getActiveAccountProfile();
    if (!account) {
      return NextResponse.json({ error: "尚未建立帳號" }, { status: 400 });
    }

    const body = (await request.json().catch(() => ({}))) as { taskType?: string };
    if (!body.taskType || !AUTOMATION_TASK_TYPES.includes(body.taskType as AutomationTaskType)) {
      return NextResponse.json({ error: "無效的任務類型" }, { status: 400 });
    }

    const result = await runTaskForAccount(account.id, body.taskType as AutomationTaskType, {
      triggeredBy: "manual",
    });

    return NextResponse.json({ result });
  } catch (error) {
    return apiRouteErrorResponse(error, "automation/run");
  }
}
