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 { resolveAuthActorId } from "../../../../lib/interactionRequestContext.js";
import { CustomerEntity } from "../../../../data/entities.js";
const metadata = {
  path: "/customers/people/[id]/emails",
  POST: {
    requireAuth: true,
    requireFeatures: ["customers.email.compose"]
  }
};
const composeSchema = z.object({
  userChannelId: z.string().uuid(),
  to: z.array(z.string().email()).min(1).max(50),
  cc: z.array(z.string().email()).max(50).optional(),
  bcc: z.array(z.string().email()).max(50).optional(),
  subject: z.string().min(1).max(500),
  body: z.string().min(1).max(2e5),
  bodyFormat: z.enum(["text", "html"]).default("html"),
  visibility: z.enum(["private", "shared"]).default("private"),
  inReplyTo: z.string().max(500).optional(),
  references: z.array(z.string().max(500)).max(50).optional(),
  parentMessageId: z.string().uuid().optional()
}).strict();
async function POST(req, context) {
  const { id: personId } = await context.params;
  if (!z.string().uuid().safeParse(personId).success) {
    return NextResponse.json({ error: "Invalid person id" }, { status: 400 });
  }
  const auth = await getAuthFromRequest(req);
  if (!auth?.sub || !auth?.tenantId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  let body;
  try {
    body = composeSchema.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 userId = resolveAuthActorId(auth);
  const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
  const organizationId = scope?.selectedId ?? auth.orgId ?? null;
  const guardResult = await validateCrudMutationGuard(container, {
    tenantId: auth.tenantId,
    organizationId,
    userId,
    resourceKind: "customers.person",
    resourceId: personId,
    operation: "custom",
    requestMethod: req.method,
    requestHeaders: req.headers
  });
  if (guardResult && !guardResult.ok) {
    return NextResponse.json(guardResult.body, { status: guardResult.status });
  }
  const em = container.resolve("em").fork();
  const dscope = { tenantId: auth.tenantId, organizationId };
  const person = await findOneWithDecryption(
    em,
    CustomerEntity,
    {
      id: personId,
      kind: "person",
      tenantId: auth.tenantId,
      organizationId,
      deletedAt: null
    },
    void 0,
    dscope
  );
  if (!person) {
    return NextResponse.json({ error: "Person not found" }, { status: 404 });
  }
  const sendAsUserService = container.resolve(
    "communicationChannelsSendAsUser"
  );
  const sendResult = await sendAsUserService(
    container,
    { userId: auth.sub, tenantId: auth.tenantId, organizationId, auth },
    {
      userChannelId: body.userChannelId,
      to: body.to,
      cc: body.cc,
      bcc: body.bcc,
      subject: body.subject,
      body: body.bodyFormat === "html" ? { html: body.body } : { plain: body.body },
      inReplyTo: body.inReplyTo,
      references: body.references,
      parentMessageId: body.parentMessageId,
      channelMetadata: {
        crmVisibility: body.visibility,
        crmPersonId: personId
      }
    }
  );
  if (!sendResult.ok) {
    return NextResponse.json({ error: sendResult.error }, { status: sendResult.status });
  }
  if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {
    await runCrudMutationGuardAfterSuccess(container, {
      tenantId: auth.tenantId,
      organizationId,
      userId,
      resourceKind: "customers.person",
      resourceId: personId,
      operation: "custom",
      requestMethod: req.method,
      requestHeaders: req.headers,
      metadata: guardResult.metadata ?? null
    });
  }
  return NextResponse.json({
    messageId: sendResult.messageId,
    threadId: sendResult.threadId,
    queuedAt: (/* @__PURE__ */ new Date()).toISOString()
  });
}
const openApi = {
  tags: ["Customers", "Email"],
  methods: {
    POST: {
      summary: "Compose + send an email anchored to a Person",
      tags: ["Customers", "Email"],
      responses: [
        { status: 200, description: "Email queued for send" },
        { status: 400, description: "Invalid person id" },
        { status: 401, description: "Unauthorized" },
        { status: 403, description: "Missing customers.email.compose feature or mutation guard rejection" },
        { status: 404, description: "Person or channel not found" },
        { status: 409, description: "Channel not connected" },
        { status: 422, description: "Invalid request body" },
        { status: 500, description: "Send failed" }
      ]
    }
  }
};
var route_default = POST;
export {
  POST,
  route_default as default,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
