import { registerCommand } from "@open-mercato/shared/lib/commands";
import { emitCrudSideEffects, emitCrudUndoSideEffects, buildChanges, requireId } from "@open-mercato/shared/lib/commands/helpers";
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import { ResourcesResourceComment } from "../data/entities.js";
import {
  resourcesResourceCommentCreateSchema,
  resourcesResourceCommentUpdateSchema
} from "../data/validators.js";
import { resourcesResourceCommentCrudEvents } from "../lib/crud.js";
import { makeCreateRedo } from "@open-mercato/shared/lib/commands/redo";
import { ensureOrganizationScope, ensureTenantScope, extractUndoPayload, requireResource, resolveResourceAuthorUserId } from "./shared.js";
import { E } from "../../../generated/entities.ids.generated.js";
const commentCrudIndexer = {
  entityType: E.resources.resources_resource_comment
};
async function loadCommentSnapshot(em, id) {
  const comment = await em.findOne(ResourcesResourceComment, { id });
  if (!comment) return null;
  return {
    id: comment.id,
    organizationId: comment.organizationId,
    tenantId: comment.tenantId,
    resourceId: typeof comment.resource === "string" ? comment.resource : comment.resource.id,
    body: comment.body,
    authorUserId: comment.authorUserId ?? null,
    appearanceIcon: comment.appearanceIcon ?? null,
    appearanceColor: comment.appearanceColor ?? null
  };
}
const createCommentCommand = {
  id: "resources.resource-comments.create",
  async execute(rawInput, ctx) {
    const parsed = resourcesResourceCommentCreateSchema.parse(rawInput);
    ensureTenantScope(ctx, parsed.tenantId);
    ensureOrganizationScope(ctx, parsed.organizationId);
    const em = ctx.container.resolve("em").fork();
    const resource = await requireResource(em, parsed.entityId, "Resource not found");
    ensureTenantScope(ctx, resource.tenantId);
    ensureOrganizationScope(ctx, resource.organizationId);
    const normalizedAuthor = await resolveResourceAuthorUserId(em, parsed.authorUserId, ctx, {
      tenantId: resource.tenantId,
      organizationId: resource.organizationId
    });
    const comment = em.create(ResourcesResourceComment, {
      organizationId: parsed.organizationId,
      tenantId: parsed.tenantId,
      resource,
      body: parsed.body,
      authorUserId: normalizedAuthor,
      appearanceIcon: parsed.appearanceIcon ?? null,
      appearanceColor: parsed.appearanceColor ?? null,
      createdAt: /* @__PURE__ */ new Date(),
      updatedAt: /* @__PURE__ */ new Date()
    });
    em.persist(comment);
    await em.flush();
    const de = ctx.container.resolve("dataEngine");
    await emitCrudSideEffects({
      dataEngine: de,
      action: "created",
      entity: comment,
      identifiers: {
        id: comment.id,
        organizationId: comment.organizationId,
        tenantId: comment.tenantId
      },
      events: resourcesResourceCommentCrudEvents,
      indexer: commentCrudIndexer
    });
    return { commentId: comment.id, authorUserId: comment.authorUserId ?? null };
  },
  captureAfter: async (_input, result, ctx) => {
    const em = ctx.container.resolve("em").fork();
    return await loadCommentSnapshot(em, result.commentId);
  },
  buildLog: async ({ result, ctx }) => {
    const { translate } = await resolveTranslations();
    const em = ctx.container.resolve("em").fork();
    const snapshot = await loadCommentSnapshot(em, result.commentId);
    return {
      actionLabel: translate("resources.audit.resourceComments.create", "Create note"),
      resourceKind: "resources.resource_comment",
      resourceId: result.commentId,
      parentResourceKind: "resources.resource",
      parentResourceId: snapshot?.resourceId ?? null,
      tenantId: snapshot?.tenantId ?? null,
      organizationId: snapshot?.organizationId ?? null,
      snapshotAfter: snapshot ?? null,
      payload: {
        undo: {
          after: snapshot ?? null
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const commentId = logEntry?.resourceId ?? null;
    if (!commentId) return;
    const em = ctx.container.resolve("em").fork();
    const existing = await em.findOne(ResourcesResourceComment, { id: commentId });
    if (existing) {
      em.remove(existing);
      await em.flush();
    }
  },
  redo: makeCreateRedo({
    entityClass: ResourcesResourceComment,
    seedFromSnapshot: (after) => ({
      id: after.id,
      organizationId: after.organizationId,
      tenantId: after.tenantId,
      body: after.body,
      authorUserId: after.authorUserId,
      appearanceIcon: after.appearanceIcon,
      appearanceColor: after.appearanceColor
    }),
    beforeRestore: async ({ em, snapshot }) => {
      const resource = await requireResource(em, snapshot.resourceId, "Resource not found");
      return { resource };
    },
    buildResult: (entity) => ({ commentId: entity.id, authorUserId: entity.authorUserId ?? null }),
    events: resourcesResourceCommentCrudEvents,
    indexer: commentCrudIndexer
  })
};
const updateCommentCommand = {
  id: "resources.resource-comments.update",
  async prepare(rawInput, ctx) {
    const parsed = resourcesResourceCommentUpdateSchema.parse(rawInput);
    const em = ctx.container.resolve("em");
    const snapshot = await loadCommentSnapshot(em, parsed.id);
    return snapshot ? { before: snapshot } : {};
  },
  async execute(rawInput, ctx) {
    const parsed = resourcesResourceCommentUpdateSchema.parse(rawInput);
    const em = ctx.container.resolve("em").fork();
    const comment = await em.findOne(ResourcesResourceComment, { id: parsed.id });
    if (!comment) throw new CrudHttpError(404, { error: "Comment not found" });
    ensureTenantScope(ctx, comment.tenantId);
    ensureOrganizationScope(ctx, comment.organizationId);
    if (parsed.entityId !== void 0) {
      const resource = await requireResource(em, parsed.entityId, "Resource not found");
      ensureTenantScope(ctx, resource.tenantId);
      ensureOrganizationScope(ctx, resource.organizationId);
      comment.resource = resource;
    }
    if (parsed.body !== void 0) comment.body = parsed.body;
    if (parsed.appearanceIcon !== void 0) comment.appearanceIcon = parsed.appearanceIcon ?? null;
    if (parsed.appearanceColor !== void 0) comment.appearanceColor = parsed.appearanceColor ?? null;
    await em.flush();
    const de = ctx.container.resolve("dataEngine");
    await emitCrudSideEffects({
      dataEngine: de,
      action: "updated",
      entity: comment,
      identifiers: {
        id: comment.id,
        organizationId: comment.organizationId,
        tenantId: comment.tenantId
      },
      events: resourcesResourceCommentCrudEvents,
      indexer: commentCrudIndexer
    });
    return { commentId: comment.id };
  },
  buildLog: async ({ snapshots, ctx }) => {
    const { translate } = await resolveTranslations();
    const before = snapshots.before;
    if (!before) return null;
    const em = ctx.container.resolve("em").fork();
    const afterSnapshot = await loadCommentSnapshot(em, before.id);
    const changes = afterSnapshot && before ? buildChanges(
      before,
      afterSnapshot,
      ["resourceId", "body", "authorUserId", "appearanceIcon", "appearanceColor"]
    ) : {};
    return {
      actionLabel: translate("resources.audit.resourceComments.update", "Update note"),
      resourceKind: "resources.resource_comment",
      resourceId: before.id,
      parentResourceKind: "resources.resource",
      parentResourceId: before.resourceId ?? null,
      tenantId: before.tenantId,
      organizationId: before.organizationId,
      snapshotBefore: before,
      snapshotAfter: afterSnapshot ?? null,
      changes,
      payload: {
        undo: {
          before,
          after: afterSnapshot ?? null
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry);
    const before = payload?.before;
    if (!before) return;
    const em = ctx.container.resolve("em").fork();
    let comment = await em.findOne(ResourcesResourceComment, { id: before.id });
    const resource = await requireResource(em, before.resourceId, "Resource not found");
    if (!comment) {
      comment = em.create(ResourcesResourceComment, {
        id: before.id,
        organizationId: before.organizationId,
        tenantId: before.tenantId,
        resource,
        body: before.body,
        authorUserId: before.authorUserId,
        appearanceIcon: before.appearanceIcon,
        appearanceColor: before.appearanceColor,
        createdAt: /* @__PURE__ */ new Date(),
        updatedAt: /* @__PURE__ */ new Date()
      });
      em.persist(comment);
    } else {
      comment.resource = resource;
      comment.body = before.body;
      comment.authorUserId = before.authorUserId;
      comment.appearanceIcon = before.appearanceIcon;
      comment.appearanceColor = before.appearanceColor;
    }
    await em.flush();
    const de = ctx.container.resolve("dataEngine");
    await emitCrudUndoSideEffects({
      dataEngine: de,
      action: "updated",
      entity: comment,
      identifiers: {
        id: comment.id,
        organizationId: comment.organizationId,
        tenantId: comment.tenantId
      },
      events: resourcesResourceCommentCrudEvents,
      indexer: commentCrudIndexer
    });
  }
};
const deleteCommentCommand = {
  id: "resources.resource-comments.delete",
  async prepare(input, ctx) {
    const id = requireId(input, "Comment id required");
    const em = ctx.container.resolve("em");
    const snapshot = await loadCommentSnapshot(em, id);
    return snapshot ? { before: snapshot } : {};
  },
  async execute(input, ctx) {
    const id = requireId(input, "Comment id required");
    const em = ctx.container.resolve("em").fork();
    const comment = await em.findOne(ResourcesResourceComment, { id });
    if (!comment) throw new CrudHttpError(404, { error: "Comment not found" });
    ensureTenantScope(ctx, comment.tenantId);
    ensureOrganizationScope(ctx, comment.organizationId);
    em.remove(comment);
    await em.flush();
    const de = ctx.container.resolve("dataEngine");
    await emitCrudSideEffects({
      dataEngine: de,
      action: "deleted",
      entity: comment,
      identifiers: {
        id: comment.id,
        organizationId: comment.organizationId,
        tenantId: comment.tenantId
      },
      events: resourcesResourceCommentCrudEvents,
      indexer: commentCrudIndexer
    });
    return { commentId: comment.id };
  },
  buildLog: async ({ snapshots }) => {
    const before = snapshots.before;
    if (!before) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("resources.audit.resourceComments.delete", "Delete note"),
      resourceKind: "resources.resource_comment",
      resourceId: before.id,
      parentResourceKind: "resources.resource",
      parentResourceId: before.resourceId ?? null,
      tenantId: before.tenantId,
      organizationId: before.organizationId,
      snapshotBefore: before,
      payload: {
        undo: {
          before
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry);
    const before = payload?.before;
    if (!before) return;
    const em = ctx.container.resolve("em").fork();
    const resource = await requireResource(em, before.resourceId, "Resource not found");
    let comment = await em.findOne(ResourcesResourceComment, { id: before.id });
    if (!comment) {
      comment = em.create(ResourcesResourceComment, {
        id: before.id,
        organizationId: before.organizationId,
        tenantId: before.tenantId,
        resource,
        body: before.body,
        authorUserId: before.authorUserId,
        appearanceIcon: before.appearanceIcon,
        appearanceColor: before.appearanceColor,
        createdAt: /* @__PURE__ */ new Date(),
        updatedAt: /* @__PURE__ */ new Date()
      });
      em.persist(comment);
    } else {
      comment.resource = resource;
      comment.body = before.body;
      comment.authorUserId = before.authorUserId;
      comment.appearanceIcon = before.appearanceIcon;
      comment.appearanceColor = before.appearanceColor;
    }
    await em.flush();
    const de = ctx.container.resolve("dataEngine");
    await emitCrudUndoSideEffects({
      dataEngine: de,
      action: "created",
      entity: comment,
      identifiers: {
        id: comment.id,
        organizationId: comment.organizationId,
        tenantId: comment.tenantId
      },
      events: resourcesResourceCommentCrudEvents,
      indexer: commentCrudIndexer
    });
  }
};
registerCommand(createCommentCommand);
registerCommand(updateCommentCommand);
registerCommand(deleteCommentCommand);
//# sourceMappingURL=comments.js.map
