import { NextResponse } from "next/server";
import { getActiveAccountProfile } from "@/lib/account-context";
import { getRulesForAccount, upsertRule } from "@/lib/automation/rules";
import { isValidCron } from "@/lib/automation/cron-match";
import { AUTOMATION_TASK_TYPES, type AutomationTaskType } from "@/lib/automation/types";
import { apiRouteErrorResponse } from "@/lib/auth/api";

export async function GET() {
  try {
    const account = await getActiveAccountProfile();
    if (!account) {
      return NextResponse.json({ error: "尚未建立帳號，請先到帳號策略新增人設" }, { status: 400 });
    }
    const rules = await getRulesForAccount(account.id);
    return NextResponse.json({
      accountId: account.id,
      accountName: account.displayName ?? account.username ?? "未命名帳號",
      automationEnabled: account.automationEnabled,
      rules,
    });
  } catch (error) {
    return apiRouteErrorResponse(error, "automation/rules");
  }
}

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 {
      taskType?: string;
      mode?: "manual" | "auto";
      dailyCap?: number;
      schedule?: string;
      enabled?: boolean;
    };

    if (!body.taskType || !AUTOMATION_TASK_TYPES.includes(body.taskType as AutomationTaskType)) {
      return NextResponse.json({ error: "無效的任務類型" }, { status: 400 });
    }
    if (body.schedule !== undefined && !isValidCron(body.schedule)) {
      return NextResponse.json({ error: "無效的 cron 排程（需 5 欄位）" }, { status: 400 });
    }
    if (body.dailyCap !== undefined && (body.dailyCap < 0 || body.dailyCap > 500)) {
      return NextResponse.json({ error: "每日上限需在 0–500 之間" }, { status: 400 });
    }

    const rule = await upsertRule(account.id, body.taskType as AutomationTaskType, {
      mode: body.mode,
      dailyCap: body.dailyCap,
      schedule: body.schedule,
      enabled: body.enabled,
    });

    return NextResponse.json({ rule });
  } catch (error) {
    return apiRouteErrorResponse(error, "automation/rules/update");
  }
}
