import {
  recordAudit
} from "./chunk-OO3I5FOB.js";
import {
  requireFeature
} from "./chunk-2N2KL4KM.js";
import {
  requireGlobalAdmin
} from "./chunk-K7DLILHK.js";
import {
  jsonOk,
  routeWrap
} from "./chunk-QSHK4MUE.js";
import {
  archiveTenant,
  createTenant,
  getTenant,
  listTenants,
  renameTenant
} from "./chunk-X27B5TCC.js";
import {
  badRequest,
  notFound
} from "./chunk-EZYKRG4W.js";

// src/handlers/tenants.ts
import { z } from "zod";
var CreateBody = z.object({
  name: z.string().min(1).max(200),
  id: z.string().regex(/^tenant_[a-z0-9_-]+$/i).optional()
});
var PatchBody = z.object({
  name: z.string().min(1).max(200).optional()
});
function handleCreateTenant(request) {
  return routeWrap(request, async ({ auth, request: req }) => {
    requireFeature("tenancy", "multi-tenancy");
    requireGlobalAdmin(auth);
    const body = await req.json().catch(() => null);
    const parsed = CreateBody.safeParse(body);
    if (!parsed.success) {
      throw badRequest(parsed.error.errors.map((e) => e.message).join("; "));
    }
    try {
      const tenant = createTenant(parsed.data);
      recordAudit({
        auth,
        action: "tenants.create",
        resource_type: "tenant",
        resource_id: tenant.id,
        tenant_id: tenant.id,
        metadata: { name: tenant.name }
      });
      return jsonOk(tenant, 201);
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      if (/UNIQUE/i.test(msg)) {
        throw badRequest("a tenant with this id already exists");
      }
      throw err;
    }
  });
}
function handleListTenants(request) {
  return routeWrap(request, async ({ auth, request: req }) => {
    requireFeature("tenancy", "multi-tenancy");
    requireGlobalAdmin(auth);
    const url = new URL(req.url);
    const includeArchived = url.searchParams.get("include_archived") === "true";
    return jsonOk({ data: listTenants({ includeArchived }) });
  });
}
function handleGetTenant(request, id) {
  return routeWrap(request, async ({ auth }) => {
    requireFeature("tenancy", "multi-tenancy");
    requireGlobalAdmin(auth);
    const tenant = getTenant(id);
    if (!tenant) throw notFound(`tenant ${id} not found`);
    return jsonOk(tenant);
  });
}
function handlePatchTenant(request, id) {
  return routeWrap(request, async ({ auth, request: req }) => {
    requireFeature("tenancy", "multi-tenancy");
    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("; "));
    }
    let changed = false;
    if (parsed.data.name) {
      const ok = renameTenant(id, parsed.data.name);
      if (!ok) throw notFound(`tenant ${id} not found`);
      changed = true;
    }
    const tenant = getTenant(id);
    if (!tenant) throw notFound(`tenant ${id} not found`);
    if (changed) {
      recordAudit({
        auth,
        action: "tenants.update",
        resource_type: "tenant",
        resource_id: id,
        tenant_id: id,
        metadata: { new_name: parsed.data.name }
      });
    }
    return jsonOk(tenant);
  });
}
function handleArchiveTenant(request, id) {
  return routeWrap(request, async ({ auth }) => {
    requireFeature("tenancy", "multi-tenancy");
    requireGlobalAdmin(auth);
    const ok = archiveTenant(id);
    if (!ok) {
      throw badRequest(
        `cannot archive tenant ${id} \u2014 not found, already archived, or the default tenant`
      );
    }
    recordAudit({
      auth,
      action: "tenants.archive",
      resource_type: "tenant",
      resource_id: id,
      tenant_id: id
    });
    return jsonOk({ ok: true, id });
  });
}

export {
  handleCreateTenant,
  handleListTenants,
  handleGetTenant,
  handlePatchTenant,
  handleArchiveTenant
};
