import { NextResponse } from "next/server";
import { findAndCountWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { InboxEmail } from "../../data/entities.js";
import { emailListQuerySchema } from "../../data/validators.js";
import { resolveRequestContext, UnauthorizedError } from "../routeHelpers.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
import { canViewEmailContent, serializeInboxEmail } from "./response.js";
const logger = createLogger("inbox_ops").child({ component: "emails" });
const metadata = {
  GET: { requireAuth: true, requireFeatures: ["inbox_ops.log.view"] }
};
async function GET(req) {
  try {
    const url = new URL(req.url);
    const query = emailListQuerySchema.parse({
      status: url.searchParams.get("status") || void 0,
      page: url.searchParams.get("page") || void 0,
      pageSize: url.searchParams.get("pageSize") || void 0
    });
    const ctx = await resolveRequestContext(req);
    const where = {
      organizationId: ctx.organizationId,
      tenantId: ctx.tenantId,
      deletedAt: null
    };
    if (query.status) {
      where.status = query.status;
    }
    const offset = (query.page - 1) * query.pageSize;
    const includeContent = await canViewEmailContent(ctx);
    const [items, total] = await findAndCountWithDecryption(
      ctx.em,
      InboxEmail,
      where,
      {
        limit: query.pageSize,
        offset,
        orderBy: { receivedAt: "DESC" }
      },
      ctx.scope
    );
    return NextResponse.json({
      items: items.map((email) => serializeInboxEmail(email, includeContent)),
      total,
      page: query.page,
      pageSize: query.pageSize,
      totalPages: Math.ceil(total / query.pageSize)
    });
  } catch (err) {
    if (err instanceof UnauthorizedError) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    logger.error("Failed to list emails", { err });
    return NextResponse.json({ error: "Failed to list emails" }, { status: 500 });
  }
}
const openApi = {
  tag: "InboxOps",
  summary: "Emails",
  methods: {
    GET: {
      summary: "List received emails",
      description: "Processing log of all received emails",
      responses: [
        { status: 200, description: "Paginated list of emails" }
      ]
    }
  }
};
export {
  GET,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
