import { sql } from "kysely";
import { runWithCacheTenant } from "@open-mercato/cache";
import {
  buildCollectionTags,
  isCrudCacheEnabled,
  resolveCrudCache
} from "@open-mercato/shared/lib/crud/cache";
import { resolveMessageContext } from "../../lib/routeHelpers.js";
import { unreadCountResponseSchema } from "../openapi.js";
const metadata = {
  GET: { requireAuth: true }
};
const UNREAD_COUNT_RESOURCE = "messages.message";
const UNREAD_COUNT_TTL_MS = 1e4;
function buildUnreadCountCacheKey(params) {
  return `messages:unread-count:u=${params.userId}:org=${params.orgId ?? "null"}`;
}
function getDb(em) {
  return em.getKysely();
}
async function GET(req) {
  const { ctx, scope } = await resolveMessageContext(req);
  const em = ctx.container.resolve("em");
  const db = getDb(em);
  const orgId = scope.organizationId ?? null;
  const cache = isCrudCacheEnabled() ? resolveCrudCache(ctx.container) : null;
  const cacheKey = cache ? buildUnreadCountCacheKey({ userId: scope.userId, orgId }) : null;
  if (cache && cacheKey) {
    const cached = await runWithCacheTenant(scope.tenantId, () => cache.get(cacheKey));
    if (typeof cached === "number") {
      return Response.json({ unreadCount: cached });
    }
  }
  let query = db.selectFrom("message_recipients as r").innerJoin("messages as m", "m.id", "r.message_id").where("r.recipient_user_id", "=", scope.userId).where("r.status", "=", "unread").where("r.deleted_at", "is", null).where("r.archived_at", "is", null).where("m.tenant_id", "=", scope.tenantId).where("m.deleted_at", "is", null);
  if (scope.organizationId) {
    query = query.where("m.organization_id", "=", scope.organizationId);
  } else {
    query = query.where("m.organization_id", "is", null);
  }
  const row = await query.select(sql`count(*)`.as("count")).executeTakeFirst();
  const count = Number(row?.count ?? 0);
  if (cache && cacheKey) {
    try {
      await runWithCacheTenant(
        scope.tenantId,
        () => cache.set(cacheKey, count, {
          ttl: UNREAD_COUNT_TTL_MS,
          tags: buildCollectionTags(UNREAD_COUNT_RESOURCE, scope.tenantId, [orgId])
        })
      );
    } catch {
    }
  }
  return Response.json({ unreadCount: count });
}
const openApi = {
  tag: "Messages",
  methods: {
    GET: {
      summary: "Get unread message count",
      responses: [
        {
          status: 200,
          description: "Unread count",
          schema: unreadCountResponseSchema
        }
      ]
    }
  }
};
export {
  GET,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
