import {
  FieldDiffSchema
} from "./chunk-SQDOBLBP.js";
import {
  INTEGRATION_MULTI_TENANT
} from "./chunk-S7C6TIIF.js";
import {
  assertTenantId
} from "./chunk-MZ6GV4YF.js";
import {
  integrationRunItems,
  integrationRuns,
  integrationSubscriptions
} from "./chunk-HNWZFNKP.js";
import {
  DRIZZLE
} from "./chunk-U64T4YZE.js";
import {
  __decorateClass,
  __decorateParam
} from "./chunk-2E224ZSN.js";

// runtime/subsystems/integration/integration-run-recorder.drizzle-backend.ts
import { Inject, Injectable, Optional } from "@nestjs/common";
import { and, desc, eq } from "drizzle-orm";
var DrizzleIntegrationRunRecorder = class {
  constructor(db, multiTenant) {
    this.db = db;
    this.multiTenant = multiTenant ?? false;
  }
  db;
  multiTenant;
  async startRun(input) {
    assertTenantId(input.tenantId, {
      multiTenant: this.multiTenant,
      operation: "startRun"
    });
    const rows = await this.db.insert(integrationRuns).values({
      subscriptionId: input.subscriptionId,
      direction: input.direction,
      action: input.action,
      status: "running",
      cursorBefore: input.cursorBefore ?? null,
      tenantId: input.tenantId ?? null
    }).returning({ id: integrationRuns.id });
    const id = rows[0]?.id;
    if (!id) {
      throw new Error("DrizzleIntegrationRunRecorder: INSERT RETURNING produced no id");
    }
    return { id };
  }
  async recordItem(input) {
    assertTenantId(input.tenantId, {
      multiTenant: this.multiTenant,
      operation: "recordItem"
    });
    FieldDiffSchema.parse(input.changedFields);
    await this.db.insert(integrationRunItems).values({
      integrationRunId: input.integrationRunId,
      entityType: input.entityType,
      externalId: input.externalId,
      localId: input.localId ?? null,
      operation: input.operation,
      status: input.status,
      changedFields: input.changedFields,
      title: input.title ?? null,
      error: input.error ?? null,
      tenantId: input.tenantId ?? null
    });
  }
  async listRecent(limit, subscriptionId, tenantId) {
    assertTenantId(tenantId, {
      multiTenant: this.multiTenant,
      operation: "listRecent"
    });
    const conditions = [];
    if (subscriptionId !== void 0) {
      conditions.push(eq(integrationRuns.subscriptionId, subscriptionId));
    }
    if (this.multiTenant) {
      conditions.push(eq(integrationRuns.tenantId, tenantId));
    }
    const where = conditions.length === 0 ? void 0 : conditions.length === 1 ? conditions[0] : and(...conditions);
    const rows = await this.db.select({
      id: integrationRuns.id,
      subscriptionId: integrationRuns.subscriptionId,
      connectionId: integrationSubscriptions.connectionId,
      status: integrationRuns.status,
      startedAt: integrationRuns.startedAt,
      completedAt: integrationRuns.completedAt,
      recordsProcessed: integrationRuns.recordsProcessed,
      tenantId: integrationRuns.tenantId
    }).from(integrationRuns).innerJoin(
      integrationSubscriptions,
      eq(integrationRuns.subscriptionId, integrationSubscriptions.id)
    ).where(where).orderBy(desc(integrationRuns.startedAt)).limit(limit);
    return rows.map((row) => ({
      id: row.id,
      subscriptionId: row.subscriptionId,
      connectionId: row.connectionId,
      status: row.status,
      startedAt: row.startedAt,
      completedAt: row.completedAt,
      recordsProcessed: row.recordsProcessed,
      tenantId: row.tenantId
    }));
  }
  async completeRun(runId, input) {
    await this.db.update(integrationRuns).set({
      status: input.status,
      recordsFound: input.recordsFound,
      recordsProcessed: input.recordsProcessed,
      cursorAfter: input.cursorAfter ?? null,
      durationMs: input.durationMs,
      error: input.error ?? null,
      completedAt: /* @__PURE__ */ new Date()
    }).where(eq(integrationRuns.id, runId));
  }
};
DrizzleIntegrationRunRecorder = __decorateClass([
  Injectable(),
  __decorateParam(0, Inject(DRIZZLE)),
  __decorateParam(1, Optional()),
  __decorateParam(1, Inject(INTEGRATION_MULTI_TENANT))
], DrizzleIntegrationRunRecorder);

export {
  DrizzleIntegrationRunRecorder
};
//# sourceMappingURL=chunk-YK5JEVLX.js.map