import { commandRegistry, registerCommand } from "@open-mercato/shared/lib/commands";
import { parseWithCustomFields } from "@open-mercato/shared/lib/commands/helpers";
import {
  activityCreateSchema,
  activityUpdateSchema
} from "../data/validators.js";
import { extractUndoPayload, resolveParentResourceKind } from "./shared.js";
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import { CUSTOMER_INTERACTION_ACTIVITY_ADAPTER_SOURCE } from "../lib/interactionCompatibility.js";
function getRequiredHandler(id) {
  const handler = commandRegistry.get(id);
  if (!handler) {
    throw new Error(`Missing command handler: ${id}`);
  }
  return handler;
}
function mapActivityCreateInput(input, custom) {
  return {
    tenantId: input.tenantId,
    organizationId: input.organizationId,
    entityId: input.entityId,
    interactionType: input.activityType,
    title: input.subject ?? null,
    body: input.body ?? null,
    occurredAt: input.occurredAt ?? null,
    status: input.occurredAt ? "done" : "planned",
    dealId: input.dealId ?? null,
    authorUserId: input.authorUserId ?? null,
    appearanceIcon: input.appearanceIcon ?? null,
    appearanceColor: input.appearanceColor ?? null,
    source: CUSTOMER_INTERACTION_ACTIVITY_ADAPTER_SOURCE,
    ...Object.keys(custom).length > 0 ? { customValues: custom } : {}
  };
}
function mapActivityUpdateInput(input, custom) {
  return {
    id: input.id,
    ...input.activityType !== void 0 ? { interactionType: input.activityType } : {},
    ...input.subject !== void 0 ? { title: input.subject ?? null } : {},
    ...input.body !== void 0 ? { body: input.body ?? null } : {},
    ...input.occurredAt !== void 0 ? {
      occurredAt: input.occurredAt ?? null,
      status: input.occurredAt ? "done" : "planned"
    } : {},
    ...input.dealId !== void 0 ? { dealId: input.dealId ?? null } : {},
    ...input.authorUserId !== void 0 ? { authorUserId: input.authorUserId ?? null } : {},
    ...input.appearanceIcon !== void 0 ? { appearanceIcon: input.appearanceIcon ?? null } : {},
    ...input.appearanceColor !== void 0 ? { appearanceColor: input.appearanceColor ?? null } : {},
    ...Object.keys(custom).length > 0 ? { customValues: custom } : {}
  };
}
function normalizeUndoCreateLogEntry(logEntry, payload) {
  const base = logEntry && typeof logEntry === "object" ? { ...logEntry } : {};
  const resourceId = typeof base.resourceId === "string" && base.resourceId.trim().length > 0 ? base.resourceId : payload?.after?.interaction.id ?? null;
  return resourceId ? { ...base, resourceId } : base;
}
const createActivityCommand = {
  id: "customers.activities.create",
  async execute(rawInput, ctx) {
    const { parsed, custom } = parseWithCustomFields(activityCreateSchema, rawInput);
    const canonicalCreate = getRequiredHandler("customers.interactions.create");
    const result = await canonicalCreate.execute(mapActivityCreateInput(parsed, custom), ctx);
    return { activityId: result.interactionId };
  },
  captureAfter: async (_input, result, ctx) => {
    const canonicalCreate = getRequiredHandler("customers.interactions.create");
    if (!canonicalCreate.captureAfter) return null;
    return canonicalCreate.captureAfter(
      {
        tenantId: ctx.auth?.tenantId ?? "00000000-0000-0000-0000-000000000000",
        organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? "00000000-0000-0000-0000-000000000000",
        entityId: "00000000-0000-0000-0000-000000000000",
        interactionType: "compatibility",
        status: "planned"
      },
      { interactionId: result.activityId },
      ctx
    );
  },
  buildLog: async ({ result, snapshots }) => {
    const { translate } = await resolveTranslations();
    const snapshot = snapshots.after;
    return {
      actionLabel: translate("customers.audit.activities.create", "Create activity"),
      resourceKind: "customers.activity",
      resourceId: result.activityId,
      parentResourceKind: resolveParentResourceKind(snapshot?.interaction.entityKind),
      parentResourceId: snapshot?.interaction.entityId ?? null,
      tenantId: snapshot?.interaction.tenantId ?? null,
      organizationId: snapshot?.interaction.organizationId ?? null,
      snapshotAfter: snapshot ?? null,
      payload: {
        undo: {
          after: snapshot ?? null
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry);
    const canonicalCreate = getRequiredHandler("customers.interactions.create");
    if (!canonicalCreate.undo) return;
    await canonicalCreate.undo({
      input: {
        tenantId: payload?.after?.interaction.tenantId ?? (typeof logEntry.tenantId === "string" ? logEntry.tenantId : "00000000-0000-0000-0000-000000000000"),
        organizationId: payload?.after?.interaction.organizationId ?? (typeof logEntry.organizationId === "string" ? logEntry.organizationId : "00000000-0000-0000-0000-000000000000"),
        entityId: payload?.after?.interaction.entityId ?? "00000000-0000-0000-0000-000000000000",
        interactionType: payload?.after?.interaction.interactionType ?? "compatibility",
        status: "planned"
      },
      ctx,
      logEntry: normalizeUndoCreateLogEntry(logEntry, payload)
    });
  },
  redo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry);
    const canonicalCreate = getRequiredHandler("customers.interactions.create");
    if (!canonicalCreate.redo) {
      throw new Error("[internal] Missing redo handler: customers.interactions.create");
    }
    const result = await canonicalCreate.redo({
      input: {
        tenantId: payload?.after?.interaction.tenantId ?? (typeof logEntry.tenantId === "string" ? logEntry.tenantId : "00000000-0000-0000-0000-000000000000"),
        organizationId: payload?.after?.interaction.organizationId ?? (typeof logEntry.organizationId === "string" ? logEntry.organizationId : "00000000-0000-0000-0000-000000000000"),
        entityId: payload?.after?.interaction.entityId ?? "00000000-0000-0000-0000-000000000000",
        interactionType: payload?.after?.interaction.interactionType ?? "compatibility",
        status: "planned"
      },
      ctx,
      logEntry: normalizeUndoCreateLogEntry(logEntry, payload)
    });
    return { activityId: result.interactionId };
  }
};
const updateActivityCommand = {
  id: "customers.activities.update",
  async prepare(rawInput, ctx) {
    const { parsed, custom } = parseWithCustomFields(activityUpdateSchema, rawInput);
    const canonicalUpdate = getRequiredHandler("customers.interactions.update");
    return canonicalUpdate.prepare?.(mapActivityUpdateInput(parsed, custom), ctx) ?? {};
  },
  async execute(rawInput, ctx) {
    const { parsed, custom } = parseWithCustomFields(activityUpdateSchema, rawInput);
    const canonicalUpdate = getRequiredHandler("customers.interactions.update");
    const result = await canonicalUpdate.execute(mapActivityUpdateInput(parsed, custom), ctx);
    return { activityId: result.interactionId };
  },
  captureAfter: async (_input, result, ctx) => {
    const canonicalUpdate = getRequiredHandler("customers.interactions.update");
    if (!canonicalUpdate.captureAfter) return null;
    return canonicalUpdate.captureAfter(
      { id: result.activityId },
      { interactionId: result.activityId },
      ctx
    );
  },
  buildLog: async ({ snapshots }) => {
    const { translate } = await resolveTranslations();
    const before = snapshots.before;
    if (!before) return null;
    const afterSnapshot = snapshots.after;
    return {
      actionLabel: translate("customers.audit.activities.update", "Update activity"),
      resourceKind: "customers.activity",
      resourceId: before.interaction.id,
      parentResourceKind: resolveParentResourceKind(before.interaction.entityKind),
      parentResourceId: before.interaction.entityId ?? null,
      tenantId: before.interaction.tenantId,
      organizationId: before.interaction.organizationId,
      snapshotBefore: before,
      snapshotAfter: afterSnapshot ?? null,
      payload: {
        undo: {
          before,
          after: afterSnapshot ?? null
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const canonicalUpdate = getRequiredHandler("customers.interactions.update");
    if (!canonicalUpdate.undo) return;
    await canonicalUpdate.undo({
      input: { id: "" },
      ctx,
      logEntry
    });
  }
};
const deleteActivityCommand = {
  id: "customers.activities.delete",
  async prepare(input, ctx) {
    const canonicalDelete = getRequiredHandler("customers.interactions.delete");
    return canonicalDelete.prepare?.(input, ctx) ?? {};
  },
  async execute(input, ctx) {
    const canonicalDelete = getRequiredHandler("customers.interactions.delete");
    const result = await canonicalDelete.execute(input, ctx);
    return { activityId: result.interactionId };
  },
  buildLog: async ({ snapshots }) => {
    const before = snapshots.before;
    if (!before) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("customers.audit.activities.delete", "Delete activity"),
      resourceKind: "customers.activity",
      resourceId: before.interaction.id,
      parentResourceKind: resolveParentResourceKind(before.interaction.entityKind),
      parentResourceId: before.interaction.entityId ?? null,
      tenantId: before.interaction.tenantId,
      organizationId: before.interaction.organizationId,
      snapshotBefore: before,
      payload: {
        undo: {
          before
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const canonicalDelete = getRequiredHandler("customers.interactions.delete");
    if (!canonicalDelete.undo) return;
    await canonicalDelete.undo({
      input: {},
      ctx,
      logEntry
    });
  }
};
registerCommand(createActivityCommand);
registerCommand(updateActivityCommand);
registerCommand(deleteActivityCommand);
//# sourceMappingURL=activities.js.map
