import { NextResponse } from "next/server";
import { sql } from "kysely";
import { runWithCacheTenant } from "@open-mercato/cache";
import { InboxProposal } from "../../../data/entities.js";
import { ALL_CATEGORIES } from "../../../data/validators.js";
import { resolveRequestContext, UnauthorizedError } from "../../routeHelpers.js";
import {
  resolveCache,
  createCountsCacheKey,
  createCountsCacheTag,
  COUNTS_CACHE_TTL_MS
} from "../../../lib/cache.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("inbox_ops").child({ component: "proposals-counts" });
const metadata = {
  GET: { requireAuth: true, requireFeatures: ["inbox_ops.proposals.view"] }
};
async function GET(req) {
  try {
    const ctx = await resolveRequestContext(req);
    const cache = resolveCache(ctx.container);
    if (cache) {
      const cacheKey = createCountsCacheKey(ctx.tenantId);
      const cached = await runWithCacheTenant(ctx.tenantId, () => cache.get(cacheKey));
      if (cached) {
        return NextResponse.json(cached);
      }
    }
    const scope = {
      organizationId: ctx.organizationId,
      tenantId: ctx.tenantId,
      deletedAt: null,
      isActive: true
    };
    const [pending, partial, accepted, rejected] = await Promise.all([
      ctx.em.count(InboxProposal, { ...scope, status: "pending" }),
      ctx.em.count(InboxProposal, { ...scope, status: "partial" }),
      ctx.em.count(InboxProposal, { ...scope, status: "accepted" }),
      ctx.em.count(InboxProposal, { ...scope, status: "rejected" })
    ]);
    const db = ctx.em.getKysely();
    const categoryRows = await db.selectFrom("inbox_proposals").select(["category", sql`count(*)`.as("count")]).where("organization_id", "=", ctx.organizationId).where("tenant_id", "=", ctx.tenantId).where("is_active", "=", true).where("deleted_at", "is", null).groupBy("category").execute();
    const byCategory = {};
    for (const cat of ALL_CATEGORIES) {
      byCategory[cat] = 0;
    }
    for (const row of categoryRows) {
      const cat = row.category;
      if (cat && cat in byCategory) {
        byCategory[cat] = Number(row.count);
      }
    }
    const responseBody = { pending, partial, accepted, rejected, byCategory };
    if (cache) {
      const cacheKey = createCountsCacheKey(ctx.tenantId);
      const tag = createCountsCacheTag(ctx.tenantId);
      try {
        await runWithCacheTenant(
          ctx.tenantId,
          () => cache.set(cacheKey, responseBody, { ttl: COUNTS_CACHE_TTL_MS, tags: [tag] })
        );
      } catch (err) {
        logger.warn("Failed to set cache", { err });
      }
    }
    return NextResponse.json(responseBody);
  } catch (err) {
    if (err instanceof UnauthorizedError) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    logger.error("Failed to get counts", { err });
    return NextResponse.json({ error: "Failed to get counts" }, { status: 500 });
  }
}
const openApi = {
  tag: "InboxOps",
  summary: "Proposal counts",
  methods: {
    GET: {
      summary: "Get proposal status and category counts",
      description: "Returns counts by status and by category for tab badges and filter dropdowns",
      responses: [
        { status: 200, description: "Status and category counts object" }
      ]
    }
  }
};
export {
  GET,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
