import { parseServiceAuth } from "@/lib/api/auth-context";
import { fail, ok } from "@/lib/response";
import { AuthError } from "@/modules/auth/errors";
import { requirePermission } from "@/modules/auth/rbac";
import { isKnownCustomerAsync } from "@/modules/auth/service-token";
import { upsertMarkupConfig } from "@/modules/pricing/markup-service";
import { parseMarkupInput } from "@/modules/pricing/markup-validation";

type MarkupBody = {
  markup_type?: unknown;
  markup_percent?: unknown;
  markup_fixed_amount?: unknown;
  operator_id?: unknown;
  remark?: unknown;
};

type RouteContext = {
  params: Promise<{ customer_id: string }>;
};

export async function PUT(request: Request, context: RouteContext) {
  let auth;
  try {
    auth = await parseServiceAuth(request);
    requirePermission(auth, "pricing:markup:write");
  } catch (error) {
    if (error instanceof AuthError) {
      return fail(error.code, error.message, error.httpStatus);
    }
    throw error;
  }

  const { customer_id: pathCustomerId } = await context.params;

  if (!(await isKnownCustomerAsync(pathCustomerId))) {
    return fail("VALIDATION_FAILED", "客户不存在", 400);
  }

  if (auth.customerId !== pathCustomerId) {
    return fail("FORBIDDEN", "无权修改该客户加价配置", 403);
  }

  let body: MarkupBody;
  try {
    body = (await request.json()) as MarkupBody;
  } catch {
    return fail("VALIDATION_FAILED", "请求体格式无效", 400);
  }

  const parsed = parseMarkupInput(body);
  if ("code" in parsed) {
    return fail("VALIDATION_FAILED", parsed.message, 400);
  }

  const operatorId =
    typeof body.operator_id === "string" && body.operator_id.trim()
      ? body.operator_id.trim()
      : auth.customerId;

  const remark =
    typeof body.remark === "string" ? body.remark.trim() || null : null;

  const config = await upsertMarkupConfig(
    pathCustomerId,
    parsed,
    operatorId,
    remark,
  );

  return ok(config);
}
