import {
  init_ids,
  newId
} from "./chunk-F4WUVOLE.js";
import {
  init_clock,
  nowMs,
  toIso
} from "./chunk-HFDLUBWN.js";
import {
  getDrizzle,
  init_drizzle
} from "./chunk-RII4M3J2.js";
import {
  schema_exports
} from "./chunk-DDJOPRB7.js";

// src/db/skills.ts
init_drizzle();
init_ids();
init_clock();
import { eq, and, isNull, lt, desc } from "drizzle-orm";
function hydrateSkill(row) {
  return {
    type: "skill",
    id: row.id,
    name: row.name,
    description: row.description ?? "",
    current_version: row.current_version ?? "1.0.0",
    created_at: toIso(row.created_at),
    updated_at: toIso(row.updated_at),
    archived_at: row.archived_at ? toIso(row.archived_at) : null
  };
}
function hydrateSkillVersion(row) {
  const filesJson = row.files_json ?? "{}";
  const files = JSON.parse(filesJson);
  const hasFiles = Object.keys(files).length > 0;
  return {
    type: "skill_version",
    id: row.id,
    skill_id: row.skill_id,
    version: row.version,
    content: row.content,
    ...hasFiles ? { files } : {},
    created_at: toIso(row.created_at)
  };
}
function createSkill(input) {
  const db = getDrizzle();
  const id = newId("skill");
  const versionId = newId("sklv");
  const now = nowMs();
  const version = "1.0.0";
  db.transaction((tx) => {
    tx.insert(schema_exports.skills).values({
      id,
      name: input.name,
      description: input.description ?? null,
      current_version: version,
      tenant_id: input.tenantId ?? null,
      created_at: now,
      updated_at: now
    }).run();
    tx.insert(schema_exports.skillVersions).values({
      id: versionId,
      skill_id: id,
      version,
      content: input.content,
      files_json: JSON.stringify(input.files ?? {}),
      created_at: now
    }).run();
  });
  return getSkill(id);
}
function getSkill(id) {
  const db = getDrizzle();
  const row = db.select().from(schema_exports.skills).where(eq(schema_exports.skills.id, id)).get();
  if (!row) return void 0;
  return hydrateSkill(row);
}
function listSkills(opts) {
  const db = getDrizzle();
  const limit = Math.min(Math.max(opts?.limit ?? 20, 1), 100);
  const includeArchived = opts?.includeArchived ?? false;
  const conditions = [];
  if (!includeArchived) conditions.push(isNull(schema_exports.skills.archived_at));
  if (opts?.cursor) {
    conditions.push(lt(schema_exports.skills.id, opts.cursor));
  }
  if (opts?.tenantId != null) {
    conditions.push(eq(schema_exports.skills.tenant_id, opts.tenantId));
  }
  const where = conditions.length ? and(...conditions) : void 0;
  const rows = where ? db.select().from(schema_exports.skills).where(where).orderBy(desc(schema_exports.skills.id)).limit(limit).all() : db.select().from(schema_exports.skills).orderBy(desc(schema_exports.skills.id)).limit(limit).all();
  return rows.map((r) => hydrateSkill(r));
}
function deleteSkill(id) {
  const db = getDrizzle();
  let deleted = false;
  db.transaction((tx) => {
    tx.delete(schema_exports.skillVersions).where(eq(schema_exports.skillVersions.skill_id, id)).run();
    const res = tx.delete(schema_exports.skills).where(eq(schema_exports.skills.id, id)).run();
    deleted = res.changes > 0;
  });
  return deleted;
}
function autoIncrement(current) {
  const parts = current.split(".");
  if (parts.length !== 3) return `${current}.1`;
  const patch = parseInt(parts[2], 10);
  return `${parts[0]}.${parts[1]}.${isNaN(patch) ? 1 : patch + 1}`;
}
function createSkillVersion(skillId, input) {
  const db = getDrizzle();
  const skill = db.select().from(schema_exports.skills).where(eq(schema_exports.skills.id, skillId)).get();
  if (!skill) return void 0;
  const version = input.version ?? autoIncrement(skill.current_version ?? "1.0.0");
  const id = newId("sklv");
  const now = nowMs();
  db.transaction((tx) => {
    tx.insert(schema_exports.skillVersions).values({
      id,
      skill_id: skillId,
      version,
      content: input.content,
      files_json: JSON.stringify(input.files ?? {}),
      created_at: now
    }).run();
    tx.update(schema_exports.skills).set({ current_version: version, updated_at: now }).where(eq(schema_exports.skills.id, skillId)).run();
  });
  return getSkillVersion(skillId, version);
}
function getSkillVersion(skillId, version) {
  const db = getDrizzle();
  let resolvedVersion = version;
  if (version === "latest") {
    const skill = db.select({ current_version: schema_exports.skills.current_version }).from(schema_exports.skills).where(eq(schema_exports.skills.id, skillId)).get();
    if (!skill?.current_version) return void 0;
    resolvedVersion = skill.current_version;
  }
  const row = db.select().from(schema_exports.skillVersions).where(
    and(
      eq(schema_exports.skillVersions.skill_id, skillId),
      eq(schema_exports.skillVersions.version, resolvedVersion)
    )
  ).get();
  if (!row) return void 0;
  return hydrateSkillVersion(row);
}
function listSkillVersions(skillId, opts) {
  const db = getDrizzle();
  const limit = Math.min(Math.max(opts?.limit ?? 20, 1), 100);
  const conditions = [eq(schema_exports.skillVersions.skill_id, skillId)];
  if (opts?.cursor) {
    conditions.push(lt(schema_exports.skillVersions.id, opts.cursor));
  }
  const rows = db.select().from(schema_exports.skillVersions).where(and(...conditions)).orderBy(desc(schema_exports.skillVersions.created_at)).limit(limit).all();
  return rows.map(
    (r) => hydrateSkillVersion(r)
  );
}
function deleteSkillVersion(skillId, version) {
  const db = getDrizzle();
  const skill = db.select().from(schema_exports.skills).where(eq(schema_exports.skills.id, skillId)).get();
  if (!skill) return { ok: false, reason: "skill not found" };
  if (skill.current_version === version) {
    return { ok: false, reason: "cannot delete the current version" };
  }
  const res = db.delete(schema_exports.skillVersions).where(
    and(
      eq(schema_exports.skillVersions.skill_id, skillId),
      eq(schema_exports.skillVersions.version, version)
    )
  ).run();
  return { ok: res.changes > 0 };
}

export {
  createSkill,
  getSkill,
  listSkills,
  deleteSkill,
  createSkillVersion,
  getSkillVersion,
  listSkillVersions,
  deleteSkillVersion
};
