import { parseAdminAuth } from "@/lib/api/admin-auth-context";
import { fail, ok } from "@/lib/response";
import { writeAudit } from "@/modules/audit/service";
import { AuthError } from "@/modules/auth/errors";
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;
  remark?: unknown;
};

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

export async function PUT(request: Request, context: RouteContext) {
  let auth;
  try {
    auth = parseAdminAuth(request);
  } 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);
  }

  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 remark =
    typeof body.remark === "string" ? body.remark.trim() || null : null;

  const config = await upsertMarkupConfig(
    pathCustomerId,
    parsed,
    auth.userId,
    remark,
  );

  await writeAudit("markup:update", auth.userId, pathCustomerId, {
    markup_type: config.markup_type,
    markup_percent: config.markup_percent,
    markup_fixed_amount: config.markup_fixed_amount,
    remark,
  });

  return ok(config);
}
