import type { ConvexHttpClient } from "convex/browser";
import {
  type CommandEnvelope,
  type BridgeContext,
} from "@/lib/documents/bridge";
import {
  recordBridgeCommandFailureArtifacts,
  recordRustBridgeCommandArtifacts,
} from "@/lib/documents/bridge-log";
import {
  executeRustBridgeMutationTransport,
  resolveRustBridgeCommandPlan,
} from "@/lib/documents/rust-runtime";

export type MediaAssetReplaceStoragePayload = {
  assetId: string;
  documentId: string;
  workspaceId: string | null;
  storageId: string;
  userId: string;
};

export type MediaAssetWritebackExecutionResult = {
  requestId: string;
  traceId: string;
  commandId: string;
  commandName: string;
};

export async function executeMediaAssetWritebackBridgeCommand(input: {
  client: ConvexHttpClient;
  context: BridgeContext;
  envelope: CommandEnvelope<MediaAssetReplaceStoragePayload>;
}): Promise<MediaAssetWritebackExecutionResult> {
  const plan = await resolveRustBridgeCommandPlan({
    context: input.context,
    envelope: input.envelope,
  });
  try {
    const transportResult = await executeRustBridgeMutationTransport({
      client: input.client,
      plan,
    });
    await recordRustBridgeCommandArtifacts({
      client: input.client,
      context: input.context,
      envelope: input.envelope,
      plan,
      result: transportResult,
    });
  } catch (error) {
    await recordBridgeCommandFailureArtifacts({
      client: input.client,
      context: input.context,
      envelope: input.envelope,
      error,
    });
    throw error;
  }

  return {
    requestId: input.context.requestId,
    traceId: input.context.traceId,
    commandId: input.envelope.commandId,
    commandName: input.envelope.name,
  };
}
