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 { rotateHostCustomerApiKey } from "@/modules/customer/customer-service";

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

export async function POST(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;

  try {
    const rotated = await rotateHostCustomerApiKey(customerId);
    await writeAudit("customer:rotate_key", auth.userId, customerId, {
      key_prefix: rotated.api_keys.find((k) => k.is_active)?.key_prefix,
    });
    return ok(rotated);
  } catch (error) {
    const message = error instanceof Error ? error.message : "轮换密钥失败";
    return fail("VALIDATION_FAILED", message, 400);
  }
}
