import {
  assertResourceTenant,
  resolveCreateTenant,
  tenantFilter
} from "./chunk-3F6VNSRK.js";
import {
  jsonOk,
  paginatedOk,
  routeWrap
} from "./chunk-KKJ5D3II.js";
import {
  archiveVault,
  createVault,
  deleteEntry,
  deleteVault,
  getEntry,
  getVault,
  listEntries,
  listVaults,
  setEntry,
  updateVault
} from "./chunk-JU6ELMEH.js";
import {
  getAgent
} from "./chunk-LGPJPAHU.js";
import {
  getDb,
  init_client
} from "./chunk-TLEKKGH7.js";
import {
  badRequest,
  conflict,
  notFound
} from "./chunk-EZYKRG4W.js";

// src/handlers/anthropic-compat/vaults.ts
import { z } from "zod";
init_client();
function getVaultTenantId(id) {
  const row = getDb().prepare(`SELECT tenant_id FROM vaults WHERE id = ?`).get(id);
  return row?.tenant_id;
}
function getAgentTenantId(id) {
  const row = getDb().prepare(`SELECT tenant_id FROM agents WHERE id = ?`).get(id);
  return row?.tenant_id;
}
function loadVaultForCaller(auth, id) {
  const tenantId = getVaultTenantId(id);
  if (tenantId === void 0) throw notFound(`vault not found: ${id}`);
  assertResourceTenant(auth, tenantId, `vault not found: ${id}`);
  const vault = getVault(id);
  if (!vault) throw notFound(`vault not found: ${id}`);
  return vault;
}
function maskValue(value) {
  if (value.length <= 6) return "******";
  return `${value.slice(0, 4)}****${value.slice(-2)}`;
}
var CreateVaultSchema = z.object({
  agent_id: z.string().min(1).optional(),
  name: z.string().min(1).optional(),
  /** Anthropic-compatible alias for `name`. */
  display_name: z.string().min(1).optional(),
  metadata: z.record(z.string().max(512)).optional(),
  /** v0.5: required for global admin, ignored for tenant users. */
  tenant_id: z.string().optional()
}).refine((data) => data.name || data.display_name, {
  message: "Either name or display_name is required"
}).refine((data) => !data.metadata || Object.keys(data.metadata).length <= 16, {
  message: "metadata must have at most 16 key-value pairs"
});
var PutEntrySchema = z.object({
  value: z.string()
});
function handleCreateVault(request) {
  return routeWrap(request, async ({ auth }) => {
    const body = await request.json();
    const parsed = CreateVaultSchema.safeParse(body);
    if (!parsed.success) throw badRequest(parsed.error.message);
    let createTenantId;
    if (parsed.data.agent_id) {
      const agentTenantId = getAgentTenantId(parsed.data.agent_id);
      if (agentTenantId === void 0) {
        throw notFound(`agent not found: ${parsed.data.agent_id}`);
      }
      assertResourceTenant(auth, agentTenantId, `agent not found: ${parsed.data.agent_id}`);
      const agent = getAgent(parsed.data.agent_id);
      if (!agent) throw notFound(`agent not found: ${parsed.data.agent_id}`);
      createTenantId = resolveCreateTenant(auth, parsed.data.tenant_id);
      if (createTenantId !== agentTenantId) {
        throw badRequest(
          `vault tenant_id must match agent tenant_id (${agentTenantId})`
        );
      }
      const vaultName2 = parsed.data.name ?? parsed.data.display_name;
      const existing = listVaults({ agent_id: parsed.data.agent_id, tenantFilter: tenantFilter(auth) });
      if (existing.some((v) => v.name === vaultName2)) {
        throw conflict(`Vault "${vaultName2}" already exists for this agent`);
      }
    } else {
      createTenantId = resolveCreateTenant(auth, parsed.data.tenant_id);
    }
    const vaultName = parsed.data.name ?? parsed.data.display_name;
    const vault = createVault({
      agent_id: parsed.data.agent_id ?? null,
      name: vaultName,
      metadata: parsed.data.metadata,
      tenant_id: createTenantId
    });
    return jsonOk(vault, 201);
  });
}
function handleListVaults(request) {
  return routeWrap(request, async ({ auth, request: req }) => {
    const url = new URL(req.url);
    const agentId = url.searchParams.get("agent_id") ?? void 0;
    const requestedLimit = Number(url.searchParams.get("limit") || "100");
    const data = listVaults({ agent_id: agentId, tenantFilter: tenantFilter(auth) });
    return paginatedOk(data, requestedLimit);
  });
}
function handleGetVault(request, id) {
  return routeWrap(request, async ({ auth }) => {
    return jsonOk(loadVaultForCaller(auth, id));
  });
}
function handleDeleteVault(request, id) {
  return routeWrap(request, async ({ auth }) => {
    loadVaultForCaller(auth, id);
    const deleted = deleteVault(id);
    if (!deleted) throw notFound(`vault not found: ${id}`);
    return jsonOk({ id, type: "vault_deleted" });
  });
}
var UpdateVaultSchema = z.object({
  display_name: z.string().min(1).max(255).optional(),
  metadata: z.record(z.string().max(512)).optional()
}).refine((data) => !data.metadata || Object.keys(data.metadata).length <= 16, {
  message: "metadata must have at most 16 key-value pairs"
});
function handleUpdateVault(request, id) {
  return routeWrap(request, async ({ auth }) => {
    loadVaultForCaller(auth, id);
    const body = await request.json();
    const parsed = UpdateVaultSchema.safeParse(body);
    if (!parsed.success) throw badRequest(parsed.error.message);
    const vault = updateVault(id, {
      display_name: parsed.data.display_name,
      metadata: parsed.data.metadata
    });
    if (!vault) throw notFound(`vault not found: ${id}`);
    return jsonOk(vault);
  });
}
function handleArchiveVault(request, id) {
  return routeWrap(request, async ({ auth }) => {
    loadVaultForCaller(auth, id);
    const ok = archiveVault(id);
    if (!ok) throw notFound(`vault not found: ${id}`);
    const vault = getVault(id);
    return jsonOk(vault);
  });
}
function handleListEntries(request, vaultId) {
  return routeWrap(request, async ({ auth }) => {
    loadVaultForCaller(auth, vaultId);
    const entries = listEntries(vaultId);
    const data = entries.map((e) => ({ key: e.key, value: maskValue(e.value) }));
    return jsonOk({ data });
  });
}
function handleGetEntry(request, vaultId, key) {
  return routeWrap(request, async ({ auth }) => {
    loadVaultForCaller(auth, vaultId);
    const entry = getEntry(vaultId, key);
    if (!entry) throw notFound(`entry not found: ${key}`);
    return jsonOk({ key: entry.key, value: maskValue(entry.value) });
  });
}
function handlePutEntry(request, vaultId, key) {
  return routeWrap(request, async ({ auth }) => {
    loadVaultForCaller(auth, vaultId);
    const body = await request.json();
    const parsed = PutEntrySchema.safeParse(body);
    if (!parsed.success) throw badRequest(parsed.error.message);
    setEntry(vaultId, key, parsed.data.value);
    return jsonOk({ key, ok: true });
  });
}
function handleDeleteEntry(request, vaultId, key) {
  return routeWrap(request, async ({ auth }) => {
    loadVaultForCaller(auth, vaultId);
    const deleted = deleteEntry(vaultId, key);
    if (!deleted) throw notFound(`entry not found: ${key}`);
    return jsonOk({ key, type: "entry_deleted" });
  });
}

export {
  loadVaultForCaller,
  handleCreateVault,
  handleListVaults,
  handleGetVault,
  handleDeleteVault,
  handleUpdateVault,
  handleArchiveVault,
  handleListEntries,
  handleGetEntry,
  handlePutEntry,
  handleDeleteEntry
};
