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 {
  updateHostCustomer,
} from "@/modules/customer/customer-service";
import type { HostCustomerStatus } from "@/modules/customer/types";

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

export async function PATCH(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: customerId } = await context.params;

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

  const payload = body as {
    name?: unknown;
    status?: unknown;
    remark?: unknown;
    embed_password?: unknown;
  };

  const input: {
    name?: string;
    status?: HostCustomerStatus;
    remark?: string | null;
    embed_password?: string;
  } = {};

  if (payload.name !== undefined) {
    if (typeof payload.name !== "string") {
      return fail("VALIDATION_FAILED", "客户名称无效", 400);
    }
    input.name = payload.name;
  }

  if (payload.status !== undefined) {
    if (payload.status !== "active" && payload.status !== "disabled") {
      return fail("VALIDATION_FAILED", "状态无效", 400);
    }
    input.status = payload.status;
  }

  if (payload.remark !== undefined) {
    input.remark =
      typeof payload.remark === "string" ? payload.remark : null;
  }

  if (payload.embed_password !== undefined) {
    if (typeof payload.embed_password !== "string") {
      return fail("VALIDATION_FAILED", "演示密码无效", 400);
    }
    input.embed_password = payload.embed_password;
  }

  try {
    const updated = await updateHostCustomer(customerId, input);
    const auditDetail: Record<string, unknown> = { ...input };
    if (auditDetail.embed_password !== undefined) {
      delete auditDetail.embed_password;
      auditDetail.embed_password_updated = true;
    }
    await writeAudit("customer:update", auth.userId, customerId, auditDetail);
    return ok(updated);
  } catch (error) {
    const message = error instanceof Error ? error.message : "更新客户失败";
    return fail("VALIDATION_FAILED", message, 400);
  }
}
