import {
  init_clock,
  nowMs
} from "./chunk-HFDLUBWN.js";
import {
  getDrizzle,
  init_drizzle
} from "./chunk-RII4M3J2.js";
import {
  schema_exports
} from "./chunk-DDJOPRB7.js";
import {
  getDb,
  init_client
} from "./chunk-TLEKKGH7.js";

// src/db/sync.ts
init_drizzle();
init_client();
init_clock();
import { eq, and } from "drizzle-orm";
function getSyncedRemoteId(localId, type) {
  const db = getDrizzle();
  const row = db.select({ remote_id: schema_exports.anthropicSync.remote_id }).from(schema_exports.anthropicSync).where(
    and(
      eq(schema_exports.anthropicSync.local_id, localId),
      eq(schema_exports.anthropicSync.resource_type, type)
    )
  ).get();
  return row?.remote_id ?? null;
}
function getSyncRow(localId, type) {
  const db = getDrizzle();
  const row = db.select().from(schema_exports.anthropicSync).where(
    and(
      eq(schema_exports.anthropicSync.local_id, localId),
      eq(schema_exports.anthropicSync.resource_type, type)
    )
  ).get();
  return row ?? null;
}
function upsertSync(localId, type, remoteId, configHash) {
  const db = getDrizzle();
  db.insert(schema_exports.anthropicSync).values({
    local_id: localId,
    resource_type: type,
    remote_id: remoteId,
    synced_at: nowMs(),
    config_hash: configHash ?? null
  }).onConflictDoUpdate({
    target: [schema_exports.anthropicSync.local_id, schema_exports.anthropicSync.resource_type],
    set: {
      remote_id: remoteId,
      synced_at: nowMs(),
      config_hash: configHash ?? null
    }
  }).run();
}
function getLocalIdByRemote(remoteId, type) {
  const db = getDb();
  const row = db.prepare("SELECT local_id FROM anthropic_sync WHERE remote_id = ? AND resource_type = ?").get(remoteId, type);
  return row?.local_id ?? null;
}
function removeSync(localId, type) {
  const db = getDrizzle();
  db.delete(schema_exports.anthropicSync).where(
    and(
      eq(schema_exports.anthropicSync.local_id, localId),
      eq(schema_exports.anthropicSync.resource_type, type)
    )
  ).run();
}
function resolveRemoteSessionId(localSessionId) {
  const remoteId = getSyncedRemoteId(localSessionId, "session");
  return remoteId ?? localSessionId;
}

export {
  getSyncedRemoteId,
  getSyncRow,
  upsertSync,
  getLocalIdByRemote,
  removeSync,
  resolveRemoteSessionId
};
