import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getActiveAccountProfile } from "@/lib/account-context";
import { apiRouteErrorResponse } from "@/lib/auth/api";

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

    const body = (await request.json().catch(() => ({}))) as { automationEnabled?: boolean };
    if (typeof body.automationEnabled !== "boolean") {
      return NextResponse.json({ error: "缺少 automationEnabled" }, { status: 400 });
    }

    const updated = await prisma.account.update({
      where: { id: account.id },
      data: { automationEnabled: body.automationEnabled },
    });

    return NextResponse.json({ automationEnabled: updated.automationEnabled });
  } catch (error) {
    return apiRouteErrorResponse(error, "automation/account");
  }
}
