import { NextResponse } from "next/server";
import { z } from "zod";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
import {
  validateCrudMutationGuard,
  runCrudMutationGuardAfterSuccess
} from "@open-mercato/shared/lib/crud/mutation-guard";
import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
import { CustomerInteraction } from "../../../../data/entities.js";
import { resolveAuthActorId } from "../../../../lib/interactionRequestContext.js";
import { emitCustomersEvent } from "../../../../events.js";
const metadata = {
  path: "/customers/interactions/[id]/visibility",
  PATCH: {
    requireAuth: true,
    requireFeatures: ["customers.email.compose"]
  }
};
const bodySchema = z.object({ visibility: z.enum(["private", "shared"]) }).strict();
async function PATCH(req, context) {
  const { id } = await context.params;
  if (!z.string().uuid().safeParse(id).success) {
    return NextResponse.json({ error: "Invalid interaction id" }, { status: 400 });
  }
  const auth = await getAuthFromRequest(req);
  if (!auth?.sub || !auth?.tenantId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  let body;
  try {
    body = bodySchema.parse(await readJsonSafe(req, null));
  } catch (err) {
    return NextResponse.json(
      { error: err instanceof Error ? err.message : "Invalid request body" },
      { status: 422 }
    );
  }
  const container = await createRequestContainer();
  const em = container.resolve("em").fork();
  const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
  const organizationId = scope?.selectedId ?? auth.orgId ?? null;
  const dscope = { tenantId: auth.tenantId, organizationId };
  const userId = resolveAuthActorId(auth);
  const guardResult = await validateCrudMutationGuard(container, {
    tenantId: auth.tenantId,
    organizationId,
    userId,
    resourceKind: "customers.interaction",
    resourceId: id,
    operation: "custom",
    requestMethod: req.method,
    requestHeaders: req.headers
  });
  if (guardResult && !guardResult.ok) {
    return NextResponse.json(guardResult.body, { status: guardResult.status });
  }
  const interaction = await findOneWithDecryption(
    em,
    CustomerInteraction,
    {
      id,
      tenantId: auth.tenantId,
      organizationId,
      deletedAt: null,
      interactionType: "email"
    },
    void 0,
    dscope
  );
  if (!interaction) {
    return NextResponse.json({ error: "Email not found" }, { status: 404 });
  }
  const isAuthor = !!interaction.authorUserId && interaction.authorUserId === auth.sub;
  if (!isAuthor) {
    return NextResponse.json({ error: "Email not found" }, { status: 404 });
  }
  if (interaction.visibility === body.visibility) {
    return NextResponse.json({ ok: true, changed: false });
  }
  const previousVisibility = interaction.visibility ?? "private";
  const commandBus = container.resolve("commandBus");
  await commandBus.execute(
    "customers.interactions.update",
    {
      input: { id, visibility: body.visibility },
      ctx: {
        container,
        auth,
        organizationScope: null,
        selectedOrganizationId: organizationId,
        organizationIds: organizationId ? [organizationId] : null
      }
    }
  );
  if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {
    await runCrudMutationGuardAfterSuccess(container, {
      tenantId: auth.tenantId,
      organizationId,
      userId,
      resourceKind: "customers.interaction",
      resourceId: id,
      operation: "custom",
      requestMethod: req.method,
      requestHeaders: req.headers,
      metadata: guardResult.metadata ?? null
    });
  }
  try {
    await emitCustomersEvent("customers.email.visibility_changed", {
      interactionId: interaction.id,
      previousVisibility,
      nextVisibility: body.visibility,
      authorUserId: interaction.authorUserId ?? null,
      actorUserId: auth.sub,
      // v1: strict owner-only — only the author reaches this point, so a
      // visibility change is never an admin bypass.
      adminBypass: false,
      tenantId: auth.tenantId,
      organizationId
    });
  } catch {
  }
  return NextResponse.json({ ok: true, changed: true });
}
const openApi = {
  tags: ["Customers", "Email"],
  methods: {
    PATCH: {
      summary: "Flip an email interaction visibility (private \u2194 shared)",
      tags: ["Customers", "Email"],
      responses: [
        { status: 200, description: "Updated" },
        { status: 400, description: "Invalid id" },
        { status: 401, description: "Unauthorized" },
        { status: 404, description: "Email not found or not visible to caller" },
        { status: 422, description: "Invalid body" }
      ]
    }
  }
};
var route_default = PATCH;
export {
  PATCH,
  route_default as default,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
