import { NextResponse } from "next/server";
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import {
  runCrudMutationGuardAfterSuccess,
  validateCrudMutationGuard
} from "@open-mercato/shared/lib/crud/mutation-guard";
import { InboxEmail } from "../../../data/entities.js";
import {
  resolveRequestContext,
  extractPathSegment,
  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"] },
  DELETE: { requireAuth: true, requireFeatures: ["inbox_ops.proposals.manage"] }
};
async function GET(req) {
  try {
    const url = new URL(req.url);
    const id = extractPathSegment(url, "emails");
    if (!id) {
      return NextResponse.json({ error: "Missing email ID" }, { status: 400 });
    }
    const ctx = await resolveRequestContext(req);
    const email = await findOneWithDecryption(
      ctx.em,
      InboxEmail,
      {
        id,
        organizationId: ctx.organizationId,
        tenantId: ctx.tenantId,
        deletedAt: null
      },
      void 0,
      ctx.scope
    );
    if (!email) {
      return NextResponse.json({ error: "Email not found" }, { status: 404 });
    }
    const includeContent = await canViewEmailContent(ctx);
    return NextResponse.json({ email: serializeInboxEmail(email, includeContent) });
  } catch (err) {
    if (err instanceof UnauthorizedError) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    logger.error("Failed to load email detail", { err });
    return NextResponse.json({ error: "Failed to load email" }, { status: 500 });
  }
}
async function DELETE(req) {
  try {
    const url = new URL(req.url);
    const id = extractPathSegment(url, "emails");
    if (!id) {
      return NextResponse.json({ error: "Missing email ID" }, { status: 400 });
    }
    const ctx = await resolveRequestContext(req);
    const guardResult = await validateCrudMutationGuard(ctx.container, {
      tenantId: ctx.tenantId,
      organizationId: ctx.organizationId,
      userId: ctx.userId,
      resourceKind: "inbox_ops:inbox_email",
      resourceId: id,
      operation: "delete",
      requestMethod: req.method,
      requestHeaders: req.headers
    });
    if (guardResult && !guardResult.ok) {
      return NextResponse.json(guardResult.body, { status: guardResult.status });
    }
    const updated = await ctx.em.nativeUpdate(
      InboxEmail,
      {
        id,
        organizationId: ctx.organizationId,
        tenantId: ctx.tenantId,
        deletedAt: null
      },
      { deletedAt: /* @__PURE__ */ new Date() }
    );
    if (updated === 0) {
      return NextResponse.json({ error: "Email not found" }, { status: 404 });
    }
    if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {
      await runCrudMutationGuardAfterSuccess(ctx.container, {
        tenantId: ctx.tenantId,
        organizationId: ctx.organizationId,
        userId: ctx.userId,
        resourceKind: "inbox_ops:inbox_email",
        resourceId: id,
        operation: "delete",
        requestMethod: req.method,
        requestHeaders: req.headers,
        metadata: guardResult.metadata ?? null
      });
    }
    return NextResponse.json({ ok: true });
  } catch (err) {
    if (err instanceof UnauthorizedError) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    logger.error("Failed to delete email", { err });
    return NextResponse.json({ error: "Failed to delete email" }, { status: 500 });
  }
}
const openApi = {
  tag: "InboxOps",
  summary: "Email detail",
  methods: {
    GET: {
      summary: "Get email detail with parsed thread",
      responses: [
        { status: 200, description: "Email detail" },
        { status: 404, description: "Email not found" }
      ]
    },
    DELETE: {
      summary: "Soft-delete an inbox email",
      responses: [
        { status: 200, description: "Email deleted" },
        { status: 404, description: "Email not found" }
      ]
    }
  }
};
export {
  DELETE,
  GET,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
