import { registerCommand } from "@open-mercato/shared/lib/commands";
import {
  parseWithCustomFields,
  setCustomFieldsIfAny,
  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 {
  loadCustomFieldSnapshot,
  diffCustomFieldChanges,
  buildCustomFieldResetMap
} from "@open-mercato/shared/lib/commands/customFieldSnapshots";
import { resolveRedoSnapshot } from "@open-mercato/shared/lib/commands/redo";
import { ResourcesResourceActivity } from "../data/entities.js";
import {
  resourcesResourceActivityCreateSchema,
  resourcesResourceActivityUpdateSchema
} from "../data/validators.js";
import { resourcesResourceActivityCrudEvents } from "../lib/crud.js";
import { ensureOrganizationScope, ensureTenantScope, extractUndoPayload, requireResource, resolveResourceAuthorUserId } from "./shared.js";
import { E } from "../../../generated/entities.ids.generated.js";
const ACTIVITY_ENTITY_ID = E.resources.resources_resource_activity;
const activityCrudIndexer = {
  entityType: E.resources.resources_resource_activity
};
async function loadActivitySnapshot(em, id) {
  const activity = await em.findOne(ResourcesResourceActivity, { id });
  if (!activity) return null;
  const custom = await loadCustomFieldSnapshot(em, {
    entityId: ACTIVITY_ENTITY_ID,
    recordId: activity.id,
    tenantId: activity.tenantId,
    organizationId: activity.organizationId
  });
  return {
    activity: {
      id: activity.id,
      organizationId: activity.organizationId,
      tenantId: activity.tenantId,
      resourceId: typeof activity.resource === "string" ? activity.resource : activity.resource.id,
      activityType: activity.activityType,
      subject: activity.subject ?? null,
      body: activity.body ?? null,
      occurredAt: activity.occurredAt ?? null,
      authorUserId: activity.authorUserId ?? null,
      appearanceIcon: activity.appearanceIcon ?? null,
      appearanceColor: activity.appearanceColor ?? null
    },
    custom
  };
}
async function setActivityCustomFields(ctx, activityId, organizationId, tenantId, values) {
  if (!values || !Object.keys(values).length) return;
  const de = ctx.container.resolve("dataEngine");
  await setCustomFieldsIfAny({
    dataEngine: de,
    entityId: ACTIVITY_ENTITY_ID,
    recordId: activityId,
    organizationId,
    tenantId,
    values,
    notify: false
  });
}
const createActivityCommand = {
  id: "resources.resource-activities.create",
  async execute(rawInput, ctx) {
    const { parsed, custom } = parseWithCustomFields(resourcesResourceActivityCreateSchema, 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 activity = em.create(ResourcesResourceActivity, {
      organizationId: parsed.organizationId,
      tenantId: parsed.tenantId,
      resource,
      activityType: parsed.activityType,
      subject: parsed.subject ?? null,
      body: parsed.body ?? null,
      occurredAt: parsed.occurredAt ?? null,
      authorUserId: normalizedAuthor,
      appearanceIcon: parsed.appearanceIcon ?? null,
      appearanceColor: parsed.appearanceColor ?? null,
      createdAt: /* @__PURE__ */ new Date(),
      updatedAt: /* @__PURE__ */ new Date()
    });
    em.persist(activity);
    await em.flush();
    await setActivityCustomFields(ctx, activity.id, parsed.organizationId, parsed.tenantId, custom);
    const de = ctx.container.resolve("dataEngine");
    await emitCrudSideEffects({
      dataEngine: de,
      action: "created",
      entity: activity,
      identifiers: {
        id: activity.id,
        organizationId: activity.organizationId,
        tenantId: activity.tenantId
      },
      events: resourcesResourceActivityCrudEvents,
      indexer: activityCrudIndexer
    });
    return { activityId: activity.id, authorUserId: activity.authorUserId ?? null };
  },
  captureAfter: async (_input, result, ctx) => {
    const em = ctx.container.resolve("em").fork();
    return await loadActivitySnapshot(em, result.activityId);
  },
  buildLog: async ({ result, ctx }) => {
    const { translate } = await resolveTranslations();
    const em = ctx.container.resolve("em").fork();
    const snapshot = await loadActivitySnapshot(em, result.activityId);
    return {
      actionLabel: translate("resources.audit.resourceActivities.create", "Create activity"),
      resourceKind: "resources.resource_activity",
      resourceId: result.activityId,
      parentResourceKind: "resources.resource",
      parentResourceId: snapshot?.activity?.resourceId ?? null,
      tenantId: snapshot?.activity.tenantId ?? null,
      organizationId: snapshot?.activity.organizationId ?? null,
      snapshotAfter: snapshot ?? null,
      payload: {
        undo: {
          after: snapshot ?? null
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const activityId = logEntry?.resourceId ?? null;
    if (!activityId) return;
    const em = ctx.container.resolve("em").fork();
    const existing = await em.findOne(ResourcesResourceActivity, { id: activityId });
    if (existing) {
      em.remove(existing);
      await em.flush();
    }
  },
  redo: async ({ logEntry, ctx }) => {
    const after = resolveRedoSnapshot(logEntry);
    if (!after) {
      throw new CrudHttpError(400, { error: "[internal] redo snapshot unavailable for activity create" });
    }
    const em = ctx.container.resolve("em").fork();
    const resource = await requireResource(em, after.activity.resourceId, "Resource not found");
    let activity = await em.findOne(ResourcesResourceActivity, { id: after.activity.id });
    if (!activity) {
      activity = em.create(ResourcesResourceActivity, {
        id: after.activity.id,
        organizationId: after.activity.organizationId,
        tenantId: after.activity.tenantId,
        resource,
        activityType: after.activity.activityType,
        subject: after.activity.subject,
        body: after.activity.body,
        occurredAt: after.activity.occurredAt,
        authorUserId: after.activity.authorUserId,
        appearanceIcon: after.activity.appearanceIcon,
        appearanceColor: after.activity.appearanceColor,
        createdAt: /* @__PURE__ */ new Date(),
        updatedAt: /* @__PURE__ */ new Date()
      });
      em.persist(activity);
    } else {
      activity.resource = resource;
      activity.activityType = after.activity.activityType;
      activity.subject = after.activity.subject;
      activity.body = after.activity.body;
      activity.occurredAt = after.activity.occurredAt;
      activity.authorUserId = after.activity.authorUserId;
      activity.appearanceIcon = after.activity.appearanceIcon;
      activity.appearanceColor = after.activity.appearanceColor;
    }
    await em.flush();
    const de = ctx.container.resolve("dataEngine");
    await emitCrudSideEffects({
      dataEngine: de,
      action: "created",
      entity: activity,
      identifiers: {
        id: activity.id,
        organizationId: activity.organizationId,
        tenantId: activity.tenantId
      },
      events: resourcesResourceActivityCrudEvents,
      indexer: activityCrudIndexer
    });
    const resetValues = buildCustomFieldResetMap(after.custom, void 0);
    if (Object.keys(resetValues).length) {
      await setCustomFieldsIfAny({
        dataEngine: de,
        entityId: ACTIVITY_ENTITY_ID,
        recordId: activity.id,
        organizationId: activity.organizationId,
        tenantId: activity.tenantId,
        values: resetValues,
        notify: false
      });
    }
    return { activityId: activity.id, authorUserId: activity.authorUserId ?? null };
  }
};
const updateActivityCommand = {
  id: "resources.resource-activities.update",
  async prepare(rawInput, ctx) {
    const parsed = resourcesResourceActivityUpdateSchema.parse(rawInput);
    const em = ctx.container.resolve("em");
    const snapshot = await loadActivitySnapshot(em, parsed.id);
    return snapshot ? { before: snapshot } : {};
  },
  async execute(rawInput, ctx) {
    const { parsed, custom } = parseWithCustomFields(resourcesResourceActivityUpdateSchema, rawInput);
    const em = ctx.container.resolve("em").fork();
    const activity = await em.findOne(ResourcesResourceActivity, { id: parsed.id });
    if (!activity) throw new CrudHttpError(404, { error: "Activity not found" });
    ensureTenantScope(ctx, activity.tenantId);
    ensureOrganizationScope(ctx, activity.organizationId);
    if (parsed.entityId !== void 0) {
      const resource = await requireResource(em, parsed.entityId, "Resource not found");
      ensureTenantScope(ctx, resource.tenantId);
      ensureOrganizationScope(ctx, resource.organizationId);
      activity.resource = resource;
    }
    if (parsed.activityType !== void 0) activity.activityType = parsed.activityType;
    if (parsed.subject !== void 0) activity.subject = parsed.subject ?? null;
    if (parsed.body !== void 0) activity.body = parsed.body ?? null;
    if (parsed.occurredAt !== void 0) activity.occurredAt = parsed.occurredAt ?? null;
    if (parsed.appearanceIcon !== void 0) activity.appearanceIcon = parsed.appearanceIcon ?? null;
    if (parsed.appearanceColor !== void 0) activity.appearanceColor = parsed.appearanceColor ?? null;
    await em.flush();
    await setActivityCustomFields(ctx, activity.id, activity.organizationId, activity.tenantId, custom);
    const de = ctx.container.resolve("dataEngine");
    await emitCrudSideEffects({
      dataEngine: de,
      action: "updated",
      entity: activity,
      identifiers: {
        id: activity.id,
        organizationId: activity.organizationId,
        tenantId: activity.tenantId
      },
      events: resourcesResourceActivityCrudEvents,
      indexer: activityCrudIndexer
    });
    return { activityId: activity.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 loadActivitySnapshot(em, before.activity.id);
    const changes = afterSnapshot && afterSnapshot.activity ? buildChanges(
      before.activity,
      afterSnapshot.activity,
      ["resourceId", "activityType", "subject", "body", "occurredAt", "authorUserId", "appearanceIcon", "appearanceColor"]
    ) : {};
    const customChanges = diffCustomFieldChanges(before.custom, afterSnapshot?.custom);
    if (Object.keys(customChanges).length) changes.custom = customChanges;
    return {
      actionLabel: translate("resources.audit.resourceActivities.update", "Update activity"),
      resourceKind: "resources.resource_activity",
      resourceId: before.activity.id,
      parentResourceKind: "resources.resource",
      parentResourceId: before.activity.resourceId ?? null,
      tenantId: before.activity.tenantId,
      organizationId: before.activity.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 activity = await em.findOne(ResourcesResourceActivity, { id: before.activity.id });
    const resource = await requireResource(em, before.activity.resourceId, "Resource not found");
    if (!activity) {
      activity = em.create(ResourcesResourceActivity, {
        id: before.activity.id,
        organizationId: before.activity.organizationId,
        tenantId: before.activity.tenantId,
        resource,
        activityType: before.activity.activityType,
        subject: before.activity.subject,
        body: before.activity.body,
        occurredAt: before.activity.occurredAt,
        authorUserId: before.activity.authorUserId,
        appearanceIcon: before.activity.appearanceIcon,
        appearanceColor: before.activity.appearanceColor,
        createdAt: /* @__PURE__ */ new Date(),
        updatedAt: /* @__PURE__ */ new Date()
      });
      em.persist(activity);
    } else {
      activity.resource = resource;
      activity.activityType = before.activity.activityType;
      activity.subject = before.activity.subject;
      activity.body = before.activity.body;
      activity.occurredAt = before.activity.occurredAt;
      activity.authorUserId = before.activity.authorUserId;
      activity.appearanceIcon = before.activity.appearanceIcon;
      activity.appearanceColor = before.activity.appearanceColor;
    }
    await em.flush();
    const de = ctx.container.resolve("dataEngine");
    await emitCrudUndoSideEffects({
      dataEngine: de,
      action: "updated",
      entity: activity,
      identifiers: {
        id: activity.id,
        organizationId: activity.organizationId,
        tenantId: activity.tenantId
      },
      events: resourcesResourceActivityCrudEvents,
      indexer: activityCrudIndexer
    });
    const resetValues = buildCustomFieldResetMap(before.custom, payload?.after?.custom);
    if (Object.keys(resetValues).length) {
      await setCustomFieldsIfAny({
        dataEngine: de,
        entityId: ACTIVITY_ENTITY_ID,
        recordId: activity.id,
        organizationId: activity.organizationId,
        tenantId: activity.tenantId,
        values: resetValues,
        notify: false
      });
    }
  }
};
const deleteActivityCommand = {
  id: "resources.resource-activities.delete",
  async prepare(input, ctx) {
    const id = requireId(input, "Activity id required");
    const em = ctx.container.resolve("em");
    const snapshot = await loadActivitySnapshot(em, id);
    return snapshot ? { before: snapshot } : {};
  },
  async execute(input, ctx) {
    const id = requireId(input, "Activity id required");
    const em = ctx.container.resolve("em").fork();
    const activity = await em.findOne(ResourcesResourceActivity, { id });
    if (!activity) throw new CrudHttpError(404, { error: "Activity not found" });
    ensureTenantScope(ctx, activity.tenantId);
    ensureOrganizationScope(ctx, activity.organizationId);
    em.remove(activity);
    await em.flush();
    const de = ctx.container.resolve("dataEngine");
    await emitCrudSideEffects({
      dataEngine: de,
      action: "deleted",
      entity: activity,
      identifiers: {
        id: activity.id,
        organizationId: activity.organizationId,
        tenantId: activity.tenantId
      },
      events: resourcesResourceActivityCrudEvents,
      indexer: activityCrudIndexer
    });
    return { activityId: activity.id };
  },
  buildLog: async ({ snapshots }) => {
    const before = snapshots.before;
    if (!before) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("resources.audit.resourceActivities.delete", "Delete activity"),
      resourceKind: "resources.resource_activity",
      resourceId: before.activity.id,
      parentResourceKind: "resources.resource",
      parentResourceId: before.activity.resourceId ?? null,
      tenantId: before.activity.tenantId,
      organizationId: before.activity.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.activity.resourceId, "Resource not found");
    let activity = await em.findOne(ResourcesResourceActivity, { id: before.activity.id });
    if (!activity) {
      activity = em.create(ResourcesResourceActivity, {
        id: before.activity.id,
        organizationId: before.activity.organizationId,
        tenantId: before.activity.tenantId,
        resource,
        activityType: before.activity.activityType,
        subject: before.activity.subject,
        body: before.activity.body,
        occurredAt: before.activity.occurredAt,
        authorUserId: before.activity.authorUserId,
        appearanceIcon: before.activity.appearanceIcon,
        appearanceColor: before.activity.appearanceColor,
        createdAt: /* @__PURE__ */ new Date(),
        updatedAt: /* @__PURE__ */ new Date()
      });
      em.persist(activity);
    } else {
      activity.resource = resource;
      activity.activityType = before.activity.activityType;
      activity.subject = before.activity.subject;
      activity.body = before.activity.body;
      activity.occurredAt = before.activity.occurredAt;
      activity.authorUserId = before.activity.authorUserId;
      activity.appearanceIcon = before.activity.appearanceIcon;
      activity.appearanceColor = before.activity.appearanceColor;
    }
    await em.flush();
    const de = ctx.container.resolve("dataEngine");
    await emitCrudUndoSideEffects({
      dataEngine: de,
      action: "created",
      entity: activity,
      identifiers: {
        id: activity.id,
        organizationId: activity.organizationId,
        tenantId: activity.tenantId
      },
      events: resourcesResourceActivityCrudEvents,
      indexer: activityCrudIndexer
    });
    const resetValues = buildCustomFieldResetMap(before.custom, void 0);
    if (Object.keys(resetValues).length) {
      await setCustomFieldsIfAny({
        dataEngine: de,
        entityId: ACTIVITY_ENTITY_ID,
        recordId: activity.id,
        organizationId: activity.organizationId,
        tenantId: activity.tenantId,
        values: resetValues,
        notify: false
      });
    }
  }
};
registerCommand(createActivityCommand);
registerCommand(updateActivityCommand);
registerCommand(deleteActivityCommand);
//# sourceMappingURL=activities.js.map
