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 { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
import { CustomerEntity } from "../../../../data/entities.js";
import { buildPersonEmailThreads } from "../../../../lib/personEmailThreads.js";
const metadata = {
  path: "/customers/people/[id]/email-threads",
  GET: {
    requireAuth: true,
    requireFeatures: ["customers.people.view"]
  }
};
async function GET(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 });
  }
  const container = await createRequestContainer();
  const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
  const organizationId = scope?.selectedId ?? auth.orgId ?? null;
  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 viewerUserId = auth.isApiKey ? null : auth.sub ?? null;
  const threads = await buildPersonEmailThreads(em, {
    personId,
    tenantId: auth.tenantId,
    organizationId,
    viewerUserId,
    // The v1 visibility filter is owner-only and ignores `userFeatures`; match
    // the sibling read routes (people/[id], interactions) by passing `undefined`
    // rather than paying an RBAC round-trip the filter discards.
    userFeatures: void 0
  });
  return NextResponse.json({ threads });
}
const openApi = {
  tags: ["Customers", "Email"],
  methods: {
    GET: {
      summary: "List a Person's email threads (Gmail-style conversation grouping)",
      tags: ["Customers", "Email"],
      responses: [
        { status: 200, description: "Email threads for the person, grouped by conversation" },
        { status: 400, description: "Invalid person id" },
        { status: 401, description: "Unauthorized" },
        { status: 403, description: "Missing customers.people.view feature" },
        { status: 404, description: "Person not found" }
      ]
    }
  }
};
var route_default = GET;
export {
  GET,
  route_default as default,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
