import {
  SUPPORTED_PROVIDERS
} from "./chunk-ZXNWEMLX.js";
import {
  addUpstreamKey,
  deleteUpstreamKey,
  disableUpstreamKey,
  enableUpstreamKey,
  getUpstreamKey,
  listUpstreamKeys
} from "./chunk-2KDG4PKE.js";
import {
  recordAudit
} from "./chunk-OO3I5FOB.js";
import {
  requireFeature
} from "./chunk-2N2KL4KM.js";
import {
  requireGlobalAdmin
} from "./chunk-K7DLILHK.js";
import {
  jsonOk,
  routeWrap
} from "./chunk-ZMMFMEXX.js";
import {
  badRequest,
  notFound
} from "./chunk-EZYKRG4W.js";

// src/handlers/upstream_keys.ts
import { z } from "zod";
var AddBody = z.object({
  provider: z.enum(SUPPORTED_PROVIDERS),
  value: z.string().min(20).max(500),
  weight: z.number().int().positive().optional()
});
var PatchBody = z.object({
  disabled: z.boolean()
});
function handleAddUpstreamKey(request) {
  return routeWrap(request, async ({ auth, request: req }) => {
    requireFeature("upstream_pool", "upstream key pool");
    requireGlobalAdmin(auth);
    const body = await req.json().catch(() => null);
    const parsed = AddBody.safeParse(body);
    if (!parsed.success) {
      throw badRequest(parsed.error.errors.map((e) => e.message).join("; "));
    }
    try {
      const added = addUpstreamKey(parsed.data);
      recordAudit({
        auth,
        action: "upstream_keys.add",
        resource_type: "upstream_key",
        resource_id: added.id,
        // Pool is global; audit entries are tenant_id=null so they land
        // in the global-admin view, not in any tenant's audit slice.
        tenant_id: null,
        metadata: { provider: added.provider, prefix: added.prefix }
      });
      return jsonOk(added, 201);
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      if (/UNIQUE/i.test(msg)) {
        throw badRequest("an identical value is already in the pool for this provider");
      }
      throw err;
    }
  });
}
function handleListUpstreamKeys(request) {
  return routeWrap(request, async ({ auth, request: req }) => {
    requireFeature("upstream_pool", "upstream key pool");
    requireGlobalAdmin(auth);
    const url = new URL(req.url);
    const provider = url.searchParams.get("provider") ?? void 0;
    return jsonOk({ data: listUpstreamKeys(provider) });
  });
}
function handleGetUpstreamKey(request, id) {
  return routeWrap(request, async ({ auth }) => {
    requireFeature("upstream_pool", "upstream key pool");
    requireGlobalAdmin(auth);
    const row = getUpstreamKey(id);
    if (!row) throw notFound(`upstream key ${id} not found`);
    return jsonOk(row);
  });
}
function handlePatchUpstreamKey(request, id) {
  return routeWrap(request, async ({ auth, request: req }) => {
    requireFeature("upstream_pool", "upstream key pool");
    requireGlobalAdmin(auth);
    const body = await req.json().catch(() => null);
    const parsed = PatchBody.safeParse(body);
    if (!parsed.success) {
      throw badRequest(parsed.error.errors.map((e) => e.message).join("; "));
    }
    const ok = parsed.data.disabled ? disableUpstreamKey(id) : enableUpstreamKey(id);
    if (!ok) throw notFound(`upstream key ${id} not found`);
    const after = getUpstreamKey(id);
    recordAudit({
      auth,
      action: parsed.data.disabled ? "upstream_keys.disable" : "upstream_keys.enable",
      resource_type: "upstream_key",
      resource_id: id,
      tenant_id: null,
      metadata: { provider: after?.provider }
    });
    return jsonOk(after);
  });
}
function handleDeleteUpstreamKey(request, id) {
  return routeWrap(request, async ({ auth }) => {
    requireFeature("upstream_pool", "upstream key pool");
    requireGlobalAdmin(auth);
    const before = getUpstreamKey(id);
    const ok = deleteUpstreamKey(id);
    if (!ok) throw notFound(`upstream key ${id} not found`);
    recordAudit({
      auth,
      action: "upstream_keys.delete",
      resource_type: "upstream_key",
      resource_id: id,
      tenant_id: null,
      metadata: before ? { provider: before.provider, prefix: before.prefix } : {}
    });
    return jsonOk({ ok: true, id });
  });
}

export {
  handleAddUpstreamKey,
  handleListUpstreamKeys,
  handleGetUpstreamKey,
  handlePatchUpstreamKey,
  handleDeleteUpstreamKey
};
