import { z } from "zod";
import { resolveRequestContext } from "@open-mercato/shared/lib/api/context";
import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import { runRouteMutationGuards } from "@open-mercato/shared/lib/crud/route-mutation-guard";
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import { resolveNotificationService } from "./notificationService.js";
const NOTIFICATION_RESOURCE_KIND = "notifications.notification";
const NOTIFICATION_SETTINGS_RESOURCE_KIND = "notifications.settings";
function formatZodIssues(error) {
  return error.issues.map((issue) => {
    const path = issue.path.length ? `${issue.path.join(".")}: ` : "";
    return `${path}${issue.message}`;
  }).join("; ");
}
async function notificationValidationErrorResponse(error) {
  const { t } = await resolveTranslations();
  const prefix = t("api.errors.invalidPayload", "Invalid request body");
  const details = formatZodIssues(error);
  return Response.json(
    { error: details ? `${prefix}: ${details}` : prefix },
    { status: 400 }
  );
}
function notificationCrudErrorResponse(error) {
  if (!isCrudHttpError(error)) return null;
  return Response.json(error.body ?? { error: "Notification request failed" }, { status: error.status });
}
async function resolveNotificationContext(req) {
  const { ctx } = await resolveRequestContext(req);
  return {
    service: resolveNotificationService(ctx.container),
    scope: {
      tenantId: ctx.auth?.tenantId ?? "",
      organizationId: ctx.selectedOrganizationId ?? null,
      userId: ctx.auth?.sub ?? null
    },
    ctx
  };
}
async function runGuardedNotificationWrite(container, scope, req, options, write) {
  const guarded = await runRouteMutationGuards({
    container,
    req,
    auth: {
      userId: scope.userId ?? "",
      tenantId: scope.tenantId,
      organizationId: scope.organizationId
    },
    input: {
      resourceKind: options.resourceKind,
      resourceId: options.resourceId ?? null,
      operation: options.operation,
      mutationPayload: options.payload ?? null
    }
  });
  if (!guarded.ok) {
    return { ok: false, response: guarded.response };
  }
  const result = await write();
  await guarded.runAfterSuccess();
  return { ok: true, result };
}
function createBulkNotificationRoute(schema, serviceMethod) {
  return async function POST(req) {
    const { service, scope, ctx } = await resolveNotificationContext(req);
    const body = await req.json().catch(() => ({}));
    const parsed = schema.safeParse(body);
    if (!parsed.success) {
      return notificationValidationErrorResponse(parsed.error);
    }
    try {
      const guarded = await runGuardedNotificationWrite(
        ctx.container,
        scope,
        req,
        {
          resourceKind: NOTIFICATION_RESOURCE_KIND,
          operation: "create",
          payload: parsed.data
        },
        () => service[serviceMethod](parsed.data, scope)
      );
      if (!guarded.ok) return guarded.response;
      const notifications = guarded.result;
      return Response.json({
        ok: true,
        count: notifications.length,
        ids: notifications.map((n) => n.id)
      }, { status: 201 });
    } catch (error) {
      const errorResponse = notificationCrudErrorResponse(error);
      if (errorResponse) return errorResponse;
      throw error;
    }
  };
}
function createBulkNotificationOpenApi(schema, summary, description) {
  return {
    POST: {
      summary,
      description,
      tags: ["Notifications"],
      requestBody: {
        required: true,
        content: {
          "application/json": {
            schema
          }
        }
      },
      responses: {
        201: {
          description: "Notifications created",
          content: {
            "application/json": {
              schema: z.object({
                ok: z.boolean(),
                count: z.number(),
                ids: z.array(z.string().uuid())
              })
            }
          }
        }
      }
    }
  };
}
function createSingleNotificationActionRoute(serviceMethod) {
  return async function PUT(req, { params }) {
    const { id } = await params;
    const { service, scope, ctx } = await resolveNotificationContext(req);
    try {
      const guarded = await runGuardedNotificationWrite(
        ctx.container,
        scope,
        req,
        {
          resourceKind: NOTIFICATION_RESOURCE_KIND,
          resourceId: id,
          operation: "update"
        },
        () => service[serviceMethod](id, scope)
      );
      if (!guarded.ok) return guarded.response;
    } catch (error) {
      const errorResponse = notificationCrudErrorResponse(error);
      if (errorResponse) return errorResponse;
      throw error;
    }
    return Response.json({ ok: true });
  };
}
function createSingleNotificationActionOpenApi(summary, description) {
  return {
    PUT: {
      summary,
      tags: ["Notifications"],
      parameters: [
        {
          name: "id",
          in: "path",
          required: true,
          schema: { type: "string", format: "uuid" }
        }
      ],
      responses: {
        200: {
          description,
          content: {
            "application/json": {
              schema: z.object({ ok: z.boolean() })
            }
          }
        }
      }
    }
  };
}
export {
  NOTIFICATION_RESOURCE_KIND,
  NOTIFICATION_SETTINGS_RESOURCE_KIND,
  createBulkNotificationOpenApi,
  createBulkNotificationRoute,
  createSingleNotificationActionOpenApi,
  createSingleNotificationActionRoute,
  notificationCrudErrorResponse,
  notificationValidationErrorResponse,
  resolveNotificationContext,
  runGuardedNotificationWrite
};
//# sourceMappingURL=routeHelpers.js.map
