Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

27.5 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { randomUUID } from "node:crypto";
import { createInterface } from "node:readline";
import { Readable } from "node:stream";
import { createGunzip, createGzip } from "node:zlib";
import type { KyselyDatabase } from "@carbon/database/client";
import { getCompanyPrivateBucket } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import type { SupabaseClient } from "@supabase/supabase-js";
import { type Kysely, sql } from "kysely";
import { nanoid } from "nanoid";
import {
  BACKUP_KIND,
  type Catalog,
  type ColumnInfo,
  type CompatibilityFinding,
  type Manifest,
  reportBackupCompatibility,
  SECRET_TABLES,
  type TableInfo
} from "../../../backups/schema";
import { buildScopeFilter, mapWithConcurrency } from "../../../backups/scope";

// Catalog introspection + compatibility live in src/backups/ (shared with the
// drift check and the ERP Backups page); re-exported so the backup jobs keep
// one import surface.
export * from "../../../backups/renames";
export * from "../../../backups/schema";
export * from "../../../backups/scope";

const log = getLogger("jobs", "company-backup");

/**
 * Shared core for company backup export/import. A backup is a folder
 * `exports/<name>/` of small objects: `manifest.json`, one
 * `tables/<table>.ndjson.gz` per non-empty table (dumped + loaded in
 * parallel), and `assets/<path>` files. Per-table NDJSON is read/written a
 * line at a time, so a huge table never materializes as one >512MB string.
 */

export const BACKUP_INTEGRATION = "company-backup";
export const EXPORTS_PREFIX = "exports";
/** Shared, env-agnostic bucket holding the onboarding backup templates. */
export const TEMPLATE_BUCKET = "company-templates";

/**
 * TEXT columns holding a storage path (`{companyId}/…/{id}.ext`). A cross-company
 * restore changes both the companyId and the embedded ids, so these are rewritten
 * in lock-step with the files they point at (`rewriteStoragePath`).
 *
 * A backup collects assets by LISTING the bucket under `{companyId}/`, not from
 * these columns — so every `modelUpload` artifact is carried regardless, and a
 * column missing here silently survives the restore still pointing at the SOURCE
 * company. Add a new `modelUpload` path column here too; the coverage test in
 * `company-backup.closure.test.ts` fails to COMPILE otherwise — it derives the
 * column set from the generated `modelUpload` row type.
 */
export const STORAGE_PATH_COLUMNS = new Set([
  "thumbnailPath",
  "modelPath",
  "originalPath",
  "optimizedModelPath",
  "glbPath",
  "graphPath",
  "pmiPath"
]);

/**
 * Item-child tables — one per `itemType` enum member — whose `id` is a
 * human-authored part number (`ADCS-001`), not an identifier. Rows match it by
 * VALUE against `item."readableId"` with no FK expressing the link, so
 * `buildIdMaps` must leave it alone: minting a fresh id orphans every row from
 * its item and the list views render empty against a full table.
 *
 * Keeping these ids is safe only because they carry no global `UNIQUE (id)` —
 * that is what separates them from the composite-PK tables the id-remap exists
 * for (`balloon`, `inspectionDocument`, …), whose preserved ids WOULD collide
 * with the source company's live rows. The two sets must stay disjoint, and an
 * explicit list is required: the schema shape alone also matches ~65 tables
 * (`workflow`, `kanban`, …) that do need remapping. Both invariants are pinned
 * in `company-backup.closure.test.ts`.
 */
export const READABLE_ID_TABLES = new Set([
  "part",
  "material",
  "consumable",
  "service",
  "tool",
  "fixture"
]);

/**
 * Prefix in the `private` bucket where onboarding demo-template assets live ONCE
 * per workspace (3D models, etc.), uploaded at deploy from the committed
 * template gz. A template import references these instead of copying the files
 * into every onboarded company's `{companyId}/` prefix.
 */
export const TEMPLATE_ASSET_PREFIX = "_templates";

/**
 * Rewrite a `{sourceCompanyId}/…` storage path to its shared template location
 * `_templates/{industryId}/…`, keeping the trailing segments (and their ids)
 * intact — the canonical asset is shared across every company onboarded from
 * the template, so ids are NOT remapped. Used both when fanning a template's
 * assets into the shared prefix at deploy and when pointing a referenced
 * import's path columns at them. A no-op if the path isn't under the source
 * company prefix.
 */
export function rewriteToTemplateAssetPath(
  path: string,
  sourceCompanyId: string,
  industryId: string
): string {
  if (path.startsWith(`${sourceCompanyId}/`)) {
    return `${TEMPLATE_ASSET_PREFIX}/${industryId}/${path.slice(
      sourceCompanyId.length + 1
    )}`;
  }
  return path;
}

/**
 * Rewrite a storage path for the target company. Swaps the leading
 * `{sourceCompanyId}/` and any path segment whose id was remapped on reseed
 * (e.g. `{co}/models/{modelId}.stl`, `{co}/thumbnails/{itemId}/{file}`). A
 * no-op for preserve-mode (same company, empty `idRewrite`). The same function
 * is applied to both the uploaded file path and the DB path columns so they
 * stay consistent.
 */
export function rewriteStoragePath(
  path: string,
  sourceCompanyId: string,
  targetCompanyId: string,
  idRewrite: Map<string, string>
): string {
  let p = path;
  if (
    sourceCompanyId !== targetCompanyId &&
    p.startsWith(`${sourceCompanyId}/`)
  ) {
    p = `${targetCompanyId}/${p.slice(sourceCompanyId.length + 1)}`;
  }
  if (idRewrite.size === 0) return p;
  return p
    .split("/")
    .map((seg) => {
      const dot = seg.indexOf(".");
      const idPart = dot >= 0 ? seg.slice(0, dot) : seg;
      const rest = dot >= 0 ? seg.slice(dot) : "";
      const mapped = idRewrite.get(idPart);
      return mapped ? mapped + rest : seg;
    })
    .join("/");
}

/**
 * Additional tables skipped in `reseed` mode — memberships, invites and
 * integration state belong to the source company's users, not to a copy.
 * The importing company already has its admin membership from onboarding.
 * (Tables whose PK is keyed by a user/employee FK — employeeJob, customer/
 * supplierAccount — are skipped automatically via `isUserScopedIdentityTable`,
 * so they don't need listing here.)
 */
export const RESEED_SKIPPED_TABLES = [
  "userToCompany",
  "employee",
  "employeeType",
  "employeeTypePermission",
  "invite",
  "externalIntegrationMapping"
];

/**
 * Tables an in-place restore must NOT wipe or reload — the caller's own access
 * and identity. Wiping these mid-restore would lock the user out of the company
 * they're restoring. The backup still carries them; they're simply left as-is.
 */
export const IN_PLACE_SKIPPED_TABLES = new Set([
  "userToCompany",
  "employee",
  "employeeType",
  "employeeTypePermission",
  "invite",
  "externalIntegrationMapping"
]);

/** Integration key for the in-place restore marker (holds the snapshot path). */
export const RESTORE_INTEGRATION = "company-restore";

export type CompanyBackup = {
  manifest: Manifest;
  data: Record<string, Record<string, unknown>[]>;
};

// ── File-per-table layout ──────────────────────────────────────────────────
// A backup is a folder `exports/<name>/` of small objects (each under the bucket
// size cap): `manifest.json`, one `tables/<table>.ndjson.gz` per non-empty table
// (dumped + loaded in parallel), and `assets/<path>` files. Bundled as one
// `.carbon.tar.gz` for cross-environment download / upload.

export function backupDir(name: string): string {
  return `${EXPORTS_PREFIX}/${name}`;
}
export function backupManifestPath(name: string): string {
  return `${EXPORTS_PREFIX}/${name}/manifest.json`;
}

/** Live progress of the current phase. `phase` is a stable KEY
 *  (`snapshot`/`seed`/`wipe`/`load`/`files`); the UI maps it to a human label per
 *  job, so the job never bakes in display copy. */
export type JobProgress = { phase: string; done: number; total: number };

const PROGRESS_THROTTLE_MS = 250;

/**
 * Wrap a marker write so same-phase ticks inside the window are dropped, but a
 * phase change or a terminal `done === total` always flushes. The wipe/load loops
 * report per table — each write is a read-then-write on a JSONB column, so
 * unthrottled it is hundreds of round-trips against the same row.
 */
export function throttleProgress(
  write: (p: JobProgress) => Promise<void>
): (p: JobProgress) => Promise<void> {
  let lastAt = 0;
  let lastPhase = "";
  return async (progress) => {
    const now = Date.now();
    const terminal = progress.done >= progress.total;
    if (
      progress.phase === lastPhase &&
      !terminal &&
      now - lastAt < PROGRESS_THROTTLE_MS
    ) {
      return;
    }
    lastPhase = progress.phase;
    lastAt = now;
    await write(progress);
  };
}

export function backupTablePath(name: string, table: string): string {
  return `${EXPORTS_PREFIX}/${name}/tables/${table}.ndjson.gz`;
}
export function backupTablesDir(name: string): string {
  return `${EXPORTS_PREFIX}/${name}/tables`;
}
export function backupAssetsDir(name: string): string {
  return `${EXPORTS_PREFIX}/${name}/assets`;
}

/**
 * Write `manifest.json` — the LAST thing written for a backup, after every table
 * file and asset is in place. Its presence is the "backup is complete" marker:
 * the UI lists a folder without a manifest as still-preparing (no size yet), and
 * restore/import refuse to read one until its manifest exists.
 */
export async function writeBackupManifest(
  client: SupabaseClient,
  companyId: string,
  name: string,
  manifest: Manifest
): Promise<void> {
  const up = await client.storage
    .from(companyId)
    .upload(backupManifestPath(name), Buffer.from(JSON.stringify(manifest)), {
      contentType: "application/json",
      upsert: true
    });
  if (up.error) throw new Error(`manifest: ${up.error.message}`);
}

/**
 * Gzip one table's rows as NDJSON (one JSON object per line). Streamed, so a huge
 * table never builds a `>512MB` string.
 */
export async function serializeTable(
  rows: Record<string, unknown>[]
): Promise<Buffer> {
  const gzip = createGzip();
  const chunks: Buffer[] = [];
  gzip.on("data", (c: Buffer) => chunks.push(c));
  const finished = new Promise<void>((resolve, reject) => {
    gzip.on("end", resolve);
    gzip.on("error", reject);
  });
  for (const row of rows) {
    await new Promise<void>((resolve, reject) => {
      gzip.write(`${JSON.stringify(row)}\n`, (err) =>
        err ? reject(err) : resolve()
      );
    });
  }
  gzip.end();
  await finished;
  return Buffer.concat(chunks);
}

/**
 * Parse a `tables/<table>.ndjson.gz` into rows. Streams the gunzip line by line,
 * so a huge table is never one giant string nor a single JSON.parse.
 */
export async function deserializeTable(
  bytes: ArrayBuffer
): Promise<Record<string, unknown>[]> {
  const gunzip = createGunzip();
  Readable.from(Buffer.from(bytes)).pipe(gunzip);
  const rl = createInterface({
    input: gunzip,
    crlfDelay: Number.POSITIVE_INFINITY
  });
  const rows: Record<string, unknown>[] = [];
  for await (const line of rl) {
    if (line) rows.push(JSON.parse(line));
  }
  return rows;
}

/** How many table files to dump/load concurrently. */
export const BACKUP_TABLE_CONCURRENCY = 6;

/** A restore/import `source` is the backup folder name. Bridge legacy single-gz
 *  sources (`exports/<name>.carbon.json.gz`) to the folder name during the
 *  transition. */
export function backupNameFromSource(source: string): string {
  return source.replace(/^exports\//, "").replace(/\.carbon\.json\.gz$/, "");
}

/**
 * Read a backup folder `exports/<name>/`: its manifest, then every table file in
 * parallel, into the in-memory `CompanyBackup` the load pipeline expects.
 */
export async function readBackup(
  client: SupabaseClient,
  companyId: string,
  name: string
): Promise<CompanyBackup> {
  const mf = await client.storage
    .from(companyId)
    .download(backupManifestPath(name));
  if (mf.error || !mf.data) {
    throw new Error(
      `Failed to download backup manifest ${name}: ${
        mf.error?.message || JSON.stringify(mf.error) || "not found"
      }`
    );
  }
  const manifest = JSON.parse(await mf.data.text()) as Manifest;
  if (manifest.kind !== BACKUP_KIND) {
    throw new Error("Not a Carbon company backup");
  }

  const data: CompanyBackup["data"] = {};
  await mapWithConcurrency(
    manifest.tables,
    BACKUP_TABLE_CONCURRENCY,
    async (t) => {
      const f = await client.storage
        .from(companyId)
        .download(backupTablePath(name, t.name));
      if (f.error || !f.data) {
        throw new Error(
          `Failed to download table ${t.name} for ${name}: ${
            f.error?.message || JSON.stringify(f.error) || "not found"
          }`
        );
      }
      data[t.name] = await deserializeTable(await f.data.arrayBuffer());
    }
  );
  return { manifest, data };
}

/**
 * Decide whether a backup can be imported into the *current* schema — the hard
 * gate the restore and import jobs call, and the boolean form of exactly the same
 * question `reportBackupCompatibility` answers in detail.
 *
 * It DELEGATES to that function rather than restating its rules. The two were
 * separate implementations kept in step by hand, and they drifted: table renames
 * reached the report but not the gate, so the pre-restore screen said "restorable"
 * and the restore then refused. A finding is `blocked` or it is not; that decision
 * now exists in one place.
 *
 * Reads only the manifest, so the verdict never depends on which table files a
 * caller happens to have loaded.
 */
export function assertBackupImportable(
  catalog: Catalog,
  backup: CompanyBackup
): { ok: true } | { ok: false; reason: string } {
  const { findings } = reportBackupCompatibility(catalog, backup.manifest);
  const blocking = findings.find((f) => f.kind === "blocked");
  if (!blocking) return { ok: true };
  return { ok: false, reason: blockingReason(blocking) };
}

/**
 * A `blocked` finding as one sentence, for a caller with nowhere to render the
 * `table`/`column` fields the UI shows beside `reason`.
 */
function blockingReason(f: CompatibilityFinding): string {
  if (f.column) {
    return `"${f.table}" now requires column "${f.column}", which this backup predates`;
  }
  return f.reason;
}

/**
 * A fresh primary-key value for a table, matching its `id` column's type as the
 * schema defines it — a real UUID for `uuid` columns, otherwise a nanoid (what
 * the `id()` default produces). Used wherever reseed/restore remaps ids, so we
 * never feed a nanoid into a uuid column.
 */
export function newIdForTable(table: TableInfo): string {
  const idCol = table.columns.find((c) => c.name === "id");
  return idCol?.udtName === "uuid" ? randomUUID() : nanoid();
}

/** Convert a pg-returned value into a JSON-safe backup value. */
export function encodeValue(value: unknown, col: ColumnInfo): unknown {
  if (value === null || value === undefined) return null;
  if (col.udtName === "bytea" && Buffer.isBuffer(value)) {
    return value.toString("base64");
  }
  if (value instanceof Date) return value.toISOString();
  return value;
}

/**
 * Convert a backup value into a parameter node-pg can bind for this
 * column. Strings pass through untyped so Postgres coerces them into
 * enums/timestamps/numerics by column type; json(b) values are stringified
 * so JS arrays inside jsonb are not mistaken for Postgres arrays.
 */
export function bindValue(value: unknown, col: ColumnInfo): unknown {
  if (value === null || value === undefined) return null;
  if (col.udtName === "bytea" && typeof value === "string") {
    return Buffer.from(value, "base64");
  }
  if (col.udtName === "json" || col.udtName === "jsonb") {
    return JSON.stringify(value);
  }
  return value;
}

/**
 * Of the given tables, return only those the target has NOT yet populated in
 * its scope (companyId or companyGroupId). Reseed import uses this so it
 * never overwrites data the target already owns — a bare clone keeps every
 * table, an identity-seeded onboard drops the ones its seed/triggers filled.
 */
export async function filterUnpopulated(
  db: Kysely<KyselyDatabase>,
  tables: TableInfo[],
  byName: Map<string, TableInfo>,
  companyId: string,
  companyGroupId: string | null
): Promise<TableInfo[]> {
  const isEmpty = await Promise.all(
    tables.map(async (t) => {
      const result = await sql<{ present: boolean }>`
        SELECT EXISTS(
          SELECT 1 FROM ${sql.id(t.name)}
          WHERE ${buildScopeFilter(t, byName, companyId, companyGroupId)}
        ) AS present
      `.execute(db);
      return !result.rows[0]?.present;
    })
  );
  return tables.filter((_, i) => isEmpty[i]);
}

/**
 * Probe whether this connection may disable triggers/FK enforcement via
 * `session_replication_role`. True on local dev (superuser); on hosted
 * Supabase it depends on the grants of the connecting role.
 */
export async function canSetReplicationRole(
  db: Kysely<KyselyDatabase>
): Promise<boolean> {
  try {
    await db.transaction().execute(async (trx) => {
      await sql`SET LOCAL session_replication_role = 'replica'`.execute(trx);
      throw new Error("__rollback__");
    });
    return true;
  } catch (err) {
    return err instanceof Error && err.message === "__rollback__";
  }
}

/**
 * The companyId-scoped tables an in-place restore may clear and reload: minus
 * the access/identity tables (kept, so the user isn't locked out) and secrets
 * (never travel). companyGroupId-scoped tables (chart of accounts, currencies)
 * are excluded — shared across the group, so a single company's restore must
 * not touch them. Returned in catalog (topological) order.
 *
 * The full set is WIPED (so a table empty in the backup ends up empty, matching
 * the snapshot exactly); only the subset with rows in the backup is reloaded.
 */
/**
 * A table whose primary key is keyed by a `user`/`employee` FK (e.g. `employeeJob`,
 * `customerAccount`, `supplierAccount`, `userToCompany`) is per-source-user
 * identity. A foreign restore / reseed collapses every user FK onto the single
 * importing user, so all such rows would collide on whatever uniqueness constraint
 * the user column participates in — a composite PK like `(id, companyId)`, OR a
 * unique index like `trainingCompletion(trainingAssignmentId, employeeId, period)`.
 * They can never be meaningfully copied to another company — skip them on both load
 * paths (the source's belong to the source's users; the target keeps its own).
 * Keys off every unique column (not just the PK) so a table that keys its user via
 * a unique index is covered automatically rather than silently colliding on load.
 */
export function isUserScopedIdentityTable(table: TableInfo): boolean {
  const uniqueCols = new Set(
    table.uniqueColumns.length > 0 ? table.uniqueColumns : table.pkColumns
  );
  return table.foreignKeys.some(
    (fk) =>
      uniqueCols.has(fk.column) &&
      (fk.refTable === "user" || fk.refTable === "employee")
  );
}

export function selectWipeableTables(
  catalog: Catalog,
  opts: { includeGroup?: boolean; remap?: boolean } = {}
): TableInfo[] {
  const skip = new Set([...SECRET_TABLES, ...IN_PLACE_SKIPPED_TABLES]);
  return catalog.tables.filter(
    (t) =>
      !skip.has(t.name) &&
      // Identity tables (per-source-user rows) are normally KEPT. But a FOREIGN
      // restore (remap) re-keys their parents' ids, and `ON DELETE CASCADE` does
      // NOT fire under `session_replication_role='replica'` — so a kept child would
      // be left dangling at a deleted/remapped parent. On remap we therefore WIPE
      // them (reverse-topo wipe clears children before parents) and never reload
      // them (the load set drops them separately). On an own restore parent ids are
      // stable, so keeping them is safe.
      (opts.remap === true || !isUserScopedIdentityTable(t)) &&
      (t.scopeColumn === "companyId" ||
        (opts.includeGroup === true && t.scopeColumn === "companyGroupId"))
  );
}

/**
 * Guard the in-place restore invariant: a KEPT table (access/secret tables that
 * survive a wipe) must not hold a NOT-NULL foreign key into a WIPED table. If it
 * did, wiping the referenced table would dangle the kept row (own restore could
 * leave it pointing at an emptied table; foreign restore remaps to new ids).
 * Currently holds — this catches future schema drift before it corrupts data.
 */
export function assertWipeSafe(
  catalog: Catalog
): { ok: true } | { ok: false; reason: string } {
  const wipeable = new Set(
    selectWipeableTables(catalog, { includeGroup: true }).map((t) => t.name)
  );
  const kept = new Set([...IN_PLACE_SKIPPED_TABLES, ...SECRET_TABLES]);
  for (const table of catalog.tables) {
    if (!kept.has(table.name)) continue;
    const colByName = new Map(table.columns.map((c) => [c.name, c]));
    for (const fk of table.foreignKeys) {
      const col = colByName.get(fk.column);
      if (col && !col.isNullable && wipeable.has(fk.refTable)) {
        return {
          ok: false,
          reason: `"${table.name}.${fk.column}" requires "${fk.refTable}", which a restore wipes — it would be left dangling`
        };
      }
    }
  }
  return { ok: true };
}

/**
 * Delete every row of the given tables for one company, in REVERSE topological
 * order (children before parents) so FK constraints hold by construction.
 * `tables` is expected in catalog (referenced-first) order; this reverses it.
 * Each table is scoped by its own column — companyId-scoped by `companyId`,
 * companyGroupId-scoped by `companyGroupId`. Run inside the caller's
 * transaction, ideally with `session_replication_role = 'replica'` set.
 */
export async function wipeScopedData(
  trx: Kysely<KyselyDatabase>,
  tables: TableInfo[],
  byName: Map<string, TableInfo>,
  scope: { companyId: string; companyGroupId: string | null },
  onProgress?: (done: number, total: number) => Promise<void>
): Promise<void> {
  const ordered = [...tables].reverse();
  for (let i = 0; i < ordered.length; i++) {
    const table = ordered[i]!;
    // buildScopeFilter scopes by parent FK for `via` tables; a null
    // companyGroupId yields `= NULL` (no match), so group data is left untouched
    // when the company has no group.
    await sql`
      DELETE FROM ${sql.id(table.name)}
      WHERE ${buildScopeFilter(table, byName, scope.companyId, scope.companyGroupId)}
    `.execute(trx);
    await onProgress?.(i + 1, ordered.length);
  }
}

// Asset copies are server-side bucket→bucket (no bytes through this process), so
// they're I/O-bound — run them concurrently rather than one at a time.
const ASSET_COPY_CONCURRENCY = 8;

/**
 * Copy one storage object server-side, overwriting the destination if it already
 * exists. `copy` has no upsert, so on a duplicate we remove the destination and
 * retry — the bytes never pass through this process either way.
 */
async function copyStorageObject(
  client: SupabaseClient,
  args: {
    srcBucket: string;
    srcPath: string;
    destBucket: string;
    destPath: string;
  }
): Promise<{ ok: boolean; error?: string }> {
  const { srcBucket, srcPath, destBucket, destPath } = args;
  const run = () =>
    client.storage
      .from(srcBucket)
      .copy(srcPath, destPath, { destinationBucket: destBucket });

  let { error } = await run();
  if (error && /exist|duplicate|409/i.test(error.message)) {
    await client.storage.from(destBucket).remove([destPath]);
    ({ error } = await run());
  }
  return { ok: !error, error: error?.message };
}

/**
 * Copy a company's storage assets (its own bucket, under `{companyId}/`) into
 * a backup's own `.assets/` folder in the same bucket. Server-side —
 * no bytes pass through this process, so a 200MB asset set costs no memory.
 * Best-effort: a per-file failure warns and continues, matching the
 * non-transactional storage semantics of restore/import.
 */
export async function copyAssetsToBackup(
  client: SupabaseClient,
  args: {
    companyId: string;
    sourcePaths: string[];
    destBucket: string;
    destPrefix: string;
  },
  onProgress?: (done: number, total: number) => Promise<void>
): Promise<{ copied: number; failed: number }> {
  const { companyId, sourcePaths, destBucket, destPrefix } = args;
  const srcBucket = getCompanyPrivateBucket(companyId);
  const total = sourcePaths.length;
  let copied = 0;
  let failed = 0;
  let done = 0;
  await mapWithConcurrency(
    sourcePaths,
    ASSET_COPY_CONCURRENCY,
    async (path) => {
      // The bucket comes from the company, never from the path: a path naming
      // another company would otherwise read that company's bucket.
      const { ok, error } = await copyStorageObject(client, {
        srcBucket,
        srcPath: path,
        destBucket,
        destPath: `${destPrefix}/${path}`
      });
      if (ok) {
        copied++;
      } else {
        failed++;
        log.warning("Failed to copy backup asset", { path, error });
      }
      await onProgress?.(++done, total);
    }
  );
  return { copied, failed };
}

/**
 * Copy a backup's stored assets back into the target company's own private
 * bucket, rewriting each path for a foreign/reseed restore (no-op for an own
 * restore). Server-side, best-effort. Every write is guarded to the target
 * company's own `{companyId}/` prefix so a malformed path can never land in
 * another tenant's space.
 */
export async function restoreAssetsFromBackup(
  client: SupabaseClient,
  args: {
    files: Array<{ path: string; included: boolean }>;
    srcBucket: string;
    srcPrefix: string;
    sourceCompanyId: string;
    companyId: string;
    idRewrite: Map<string, string>;
  },
  onProgress?: (done: number, total: number) => Promise<void>
): Promise<{ copied: number; failed: number }> {
  const { files, srcBucket, srcPrefix, sourceCompanyId, companyId, idRewrite } =
    args;
  const included = files.filter((f) => f.included);
  const total = included.length;
  let copied = 0;
  let failed = 0;
  let done = 0;
  await mapWithConcurrency(included, ASSET_COPY_CONCURRENCY, async (file) => {
    const targetPath = rewriteStoragePath(
      file.path,
      sourceCompanyId,
      companyId,
      idRewrite
    );
    if (!targetPath.startsWith(`${companyId}/`)) {
      log.warning("Skipping backup asset outside target company prefix", {
        path: file.path,
        targetPath
      });
      await onProgress?.(++done, total);
      return;
    }
    const { ok, error } = await copyStorageObject(client, {
      srcBucket,
      srcPath: `${srcPrefix}/${file.path}`,
      destBucket: getCompanyPrivateBucket(companyId),
      destPath: targetPath
    });
    if (ok) {
      copied++;
    } else {
      failed++;
      log.warning("Failed to restore backup asset", {
        path: file.path,
        targetPath,
        error
      });
    }
    await onProgress?.(++done, total);
  });
  return { copied, failed };
}

/**
 * Remove every object under a prefix in a bucket (e.g. a backup's `.assets/`
 * folder), recursing into subfolders, so deleting a backup or snapshot leaves no
 * orphaned files.
 */
export async function removeStoragePrefix(
  client: SupabaseClient,
  bucket: string,
  prefix: string
): Promise<void> {
  const { data, error } = await client.storage
    .from(bucket)
    .list(prefix, { limit: 1000 });
  if (error || !data) return;
  const files: string[] = [];
  for (const entry of data) {
    const path = `${prefix}/${entry.name}`;
    if (entry.id === null) {
      await removeStoragePrefix(client, bucket, path);
    } else {
      files.push(path);
    }
  }
  if (files.length > 0) {
    await client.storage.from(bucket).remove(files);
  }
}