import {
  init_ids,
  newId
} from "./chunk-F4WUVOLE.js";
import {
  init_clock,
  nowMs,
  toIso
} from "./chunk-HFDLUBWN.js";
import {
  getDb,
  init_client
} from "./chunk-TLEKKGH7.js";

// src/db/user-profiles.ts
init_client();
init_ids();
init_clock();
function hydrate(row) {
  return {
    type: "user_profile",
    id: row.id,
    external_id: row.external_id,
    display_name: row.display_name,
    trust_grants: JSON.parse(row.trust_grants_json),
    tenant_id: row.tenant_id,
    created_at: toIso(row.created_at),
    updated_at: toIso(row.updated_at)
  };
}
function createUserProfile(input) {
  const db = getDb();
  const id = newId("uprof");
  const now = nowMs();
  db.prepare(
    `INSERT INTO user_profiles (id, external_id, display_name, trust_grants_json, tenant_id, created_at, updated_at)
     VALUES (?, ?, ?, ?, ?, ?, ?)`
  ).run(
    id,
    input.external_id ?? null,
    input.display_name ?? null,
    JSON.stringify(input.trust_grants ?? []),
    input.tenant_id ?? null,
    now,
    now
  );
  return getUserProfile(id);
}
function getUserProfile(id) {
  const db = getDb();
  const row = db.prepare(`SELECT * FROM user_profiles WHERE id = ?`).get(id);
  return row ? hydrate(row) : null;
}
function listUserProfiles(opts) {
  const db = getDb();
  const limit = Math.min(opts.limit ?? 50, 100);
  const parts = [];
  const args = [];
  if (opts.tenant_id) {
    parts.push("tenant_id = ?");
    args.push(opts.tenant_id);
  }
  if (opts.after_id) {
    parts.push("id > ?");
    args.push(opts.after_id);
  }
  const where = parts.length > 0 ? `WHERE ${parts.join(" AND ")}` : "";
  const rows = db.prepare(
    `SELECT * FROM user_profiles ${where} ORDER BY id ASC LIMIT ?`
  ).all(...args, limit + 1);
  const hasMore = rows.length > limit;
  if (hasMore) rows.pop();
  return { data: rows.map(hydrate), has_more: hasMore };
}
function updateUserProfile(id, input) {
  const db = getDb();
  const existing = db.prepare(`SELECT * FROM user_profiles WHERE id = ?`).get(id);
  if (!existing) return null;
  const now = nowMs();
  const parts = ["updated_at = ?"];
  const args = [now];
  if (input.external_id !== void 0) {
    parts.push("external_id = ?");
    args.push(input.external_id);
  }
  if (input.display_name !== void 0) {
    parts.push("display_name = ?");
    args.push(input.display_name);
  }
  if (input.trust_grants !== void 0) {
    parts.push("trust_grants_json = ?");
    args.push(JSON.stringify(input.trust_grants));
  }
  db.prepare(`UPDATE user_profiles SET ${parts.join(", ")} WHERE id = ?`).run(...args, id);
  return getUserProfile(id);
}

export {
  createUserProfile,
  getUserProfile,
  listUserProfiles,
  updateUserProfile
};
